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;
}
}