Spring注解lettuce实战案例

lettuce是基于netty实现的,当多线程使用同一连接实例时,是线程安全的。而Jedis多线程使用同一个连接池时,是线程不安全的,想要线程安全需要配置连接池。现在SpringBoot也支持使用lettuce作为redis的客户端

配置lettuce 客户端

@Configuration
public class LettuceClient {

  RedisClient client=RedisClient.create(RedisURI.create("redis://localhost:6379"));
  StatefulRedisConnection<String,String> connect=client.connect();

  @Bean
  public RedisCommands<String,String> commands(){
      return connect.sync();
  }


}

注入

    @Autowired
    RedisCommands<String,String> commands;

使用

 public User findUserByNameAndPassword(String t_userName,String t_userPassword){

         //1.从redis中查询
        String password = commands.get(t_userName);
        User user=null;
        //2.判断集合是否为空
          if (password == null){
            //3.如果为空从数据库中查询

              user=userDao.findByNameAndPassword(t_userName,t_userPassword);
              commands.set(user.getT_userName(),user.getT_userPassword());
               return user;
          }else {
              //4.如果不为空
              if (password != t_userPassword){
                  return null;
              }

              user.setT_userName(t_userName);
              user.setT_userPassword(t_userPassword);

              return user;
          }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章