springboot 操作redis
目录
redis 常用命令
整合spring data redis
Spring Boot 提供了对 Redis 集成的组件包:spring-boot-starter-data-redis,它依赖于 spring-data-redis 和 lettuce。
Lettuce:是一个可伸缩线程安全的 Redis 客户端,多个线程可以共享同一个 RedisConnection,它利用优秀 Netty NIO 框架来高效地管理多个连接。
Spring Data Redis:是 Spring Data 项目中的一个主要模块,实现了对 Redis 客户端 API 的高度封装,使对 Redis 的操作更加便捷。
引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
引入 commons-pool 2 是因为 Lettuce 需要使用 commons-pool 2 创建 Redis 连接池。
application 配置
spring:
redis:
database: 0 # Redis 数据库索引(默认为 0)
host: 192.168.161.3 # Redis 服务器地址
port: 6379 # Redis 服务器连接端口
password: 123456 # Redis 服务器连接密码(默认为空)
lettuce:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制) 默认 8
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-idle: 8 # 连接池中的最大空闲连接 默认 8
min-idle: 0 # 连接池中的最小空闲连接 默认 0
redis模板封装类
StringRedisTemplate 与 RedisTemplate 的封装的 Reids 操作要比我们第二节讲的自己调用 Jedis 的 API 的方式更优雅了一步。
redis模板封装类
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作 hash
redisTemplate.opsForList();//操作 list
redisTemplate.opsForSet();//操作 set
redisTemplate.opsForZSet();//操作有序 set
依赖注入
public class Example {
// 注入RedisTemplate,更通用
@Autowired
private RedisTemplate<String, String> template;
}
代码测试
准备数据对象
@Data
public class Person implements Serializable {
private static final long serialVersionUID = -8985545025228238754L;
String id;
String firstname;
String lastname;
Address address;
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
}
@Data
public class Address implements Serializable {
private static final long serialVersionUID = -8985545025228238771L;
String city;
String country;
public Address(String city, String country) {
this.city = city;
this.country = country;
}
}
使用redisTemplate
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisConfigTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Resource(name = "redisTemplate")
private ValueOperations<String,Object> valueOperations;
@Resource(name = "redisTemplate")
private HashOperations<String, String, Object> hashOperations;
@Resource(name = "redisTemplate")
private ListOperations<String, Object> listOperations;
@Resource(name = "redisTemplate")
private SetOperations<String, Object> setOperations;
@Resource(name = "redisTemplate")
private ZSetOperations<String, Object> zSetOperations;
}
value存储对象
@Test
public void testValueObj() throws Exception{
Person person = new Person("boke","byrant");
person.setAddress(new Address("南京","中国"));
//ValueOperations<String,Object> operations = redisTemplate.opsForValue();
valueOperations.set("player:1",person,20,TimeUnit.SECONDS); //10秒之后数据消失
Person getBack = (Person)valueOperations.get("player:1");
System.out.println(getBack);
}
集合存储对象
@Test
public void testSetOperation() throws Exception{
Person person = new Person("boke","byrant");
Person person2 = new Person("curry","stephen");
setOperations.add("playerset",person,person2);
Set<Object> result = setOperations.members("playerset");
System.out.println(result);
}
hash集合存储对象
@Test
public void HashOperations() throws Exception{
Person person = new Person("boke","byrant");
hashOperations.put("hash:player","firstname",person.getFirstname());
hashOperations.put("hash:player","lastname",person.getLastname());
hashOperations.put("hash:player","address",person.getAddress());
System.out.println(hashOperations.get("hash:player","firstname"));
}
List 存储对象
@Test
public void ListOperations() throws Exception{
listOperations.leftPush("list:player",new Person("boke","byrant"));
listOperations.leftPush("list:player",new Person("Jordan","Mikel"));
listOperations.leftPush("list:player",new Person("curry","stephen"));
System.out.println(listOperations.leftPop("list:player"));
}
解决key-value乱码问题
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//重点在这四行代码
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
乱码问题的症结在于对象的序列化问题,RedisTemplate默认使用的是JdkSerializationRedisSerializer,StringRedisTemplate默认使用的是StringRedisSerializer。
同时要注意Redis 字符编码集设置。