lettuce是基于netty实现的,当多线程使用同一连接实例时,是线程安全的。而Jedis多线程使用同一个连接池时,是线程不安全的,想要线程安全需要配置连接池。现在SpringBoot也支持使用lettuce作为redis的客户端
pom文件
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
配置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;
}
}