SpringDataRedis客户端详解
SpringData是Spring中数据操作的模块,包含对各种数据库的集成,其中对Redis的集成模块就叫做SpringDataRedis,官网地址:https://spring.io/projects/spring-data-redis
- 提供了对不同Redis客户端的整合(Lettuce和Jedis)
- 提供了RedisTemplate统一API来操作Redis
- 支持Redis的发布订阅模型
- 支持Redis哨兵和Redis集群
- 支持基于Lettuce的响应式编程
- 支持基于JDK、JSON、字符串、Spring对象的数据序列化及反序列化
- 支持基于Redis的JDKCollection实现
SpringDataRedis中提供了RedisTemplate工具类,其中封装了各种对Redis的操作。并且将不同数据类型的操作API封装到了不同的类型中:
1. 快速入门
SpringBoot已经提供了对SpringDataRedis的支持,使用非常简单。
- pom.xml文件中引入依赖
<!--redis依赖-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--common-pool-->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency>
<!--Jackson依赖-->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency>
- application.yaml配置文件中 配置Redis
SpringDataRedis底层原理为 lettuce,如果想使用jedis,需要导入对应的依赖
spring:redis:host: 192.168.150.101port: 6379password: 123321lettuce:pool:max-active: 8max-idle: 8min-idle: 0max-wait: 100ms
- 自定义序列化
RedisTemplate可以接收任意Object作为值写入Redis,只不过写入前会把Object序列化为字节形式,默认是采用JDK序列化,导致可读性差和内存占用大
自定义RedisTemplate的序列化方式:
package com.example.springdataredisdemo.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;import javax.annotation.Resource;@Configuration
public class RedisConfig {@Bean@Resourcepublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){// 创建RedisTemplate对象RedisTemplate<String, Object> template = new RedisTemplate<>();// 设置连接工厂template.setConnectionFactory(connectionFactory);// 创建JSON序列化工具GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();// 设置Key的序列化template.setKeySerializer(RedisSerializer.string());template.setHashKeySerializer(RedisSerializer.string());// 设置Value的序列化template.setValueSerializer(jsonRedisSerializer);template.setHashValueSerializer(jsonRedisSerializer);// 返回return template;}
}
- 编写测试类
package com.example.springdataredisdemo;import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;@SpringBootTest
class SpringDataRedisDemoApplicationTests {@Resourceprivate RedisTemplate<String, Object> redisTemplate;// value值为字符串@Testvoid testString() {// 写入一条String数据redisTemplate.opsForValue().set("name", "黄宇诗是一个笨蛋");// 获取string数据Object name = redisTemplate.opsForValue().get("name");System.out.println("name = " + name);}// value值为User对象@Testpublic void testUser(){redisTemplate.opsForValue().set("heima:user:7",new User(7,"lyq",19));User user = (User) redisTemplate.opsForValue().get("heima:user:7");System.out.println("user: " + user);}}
这里采用了JSON序列化来代替默认的JDK序列化方式。最终结果如图:
整体可读性有了很大提升,并且能将Java对象自动的序列化为JSON字符串,并且查询时能自动把JSON反序列化为Java对象。不过,其中记录了序列化时对应的class名称,目的是为了查询时实现自动反序列化。这会带来额外的内存开销。
- StringRedisTemplate
为了节省内存空间,我们可以不使用JSON序列化器来处理value,而是统一使用String序列化器,要求只能存储String类型的key和value。当需要存储Java对象时,手动完成对象的序列化和反序列化。
SpringDataRedis就提供了RedisTemplate的子类:StringRedisTemplate,它的key和value的序列化方式默认就是String方式。
package com.example.springdataredisdemo;import com.example.springdataredisdemo.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.annotation.Resource;@SpringBootTest
class Tests {@Resourceprivate StringRedisTemplate stringRedisTemplate;// JSON序列化工具private static final ObjectMapper mapper = new ObjectMapper();@Testpublic void testString() {// 写入一条String数据stringRedisTemplate.opsForValue().set("name", "黄宇诗");// 获取string数据Object name = stringRedisTemplate.opsForValue().get("name");System.out.println("name = " + name);}@Testpublic void testUser() throws JsonProcessingException {// 创建对象User user = new User(8,"陆云巧", 19);// 手动序列化String json = mapper.writeValueAsString(user);// 写入数据stringRedisTemplate.opsForValue().set("heima:user:8", json);// 获取数据String jsonUser = stringRedisTemplate.opsForValue().get("heima:user:8");// 手动反序列化User user1 = mapper.readValue(jsonUser, User.class);System.out.println("user1 = " + user1);}// 测试Hash类型@Testpublic void testHash(){stringRedisTemplate.opsForHash().put("heima:user:9","id","9");stringRedisTemplate.opsForHash().put("heima:user:9","name","孙彩霞");Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("heima:user:9");System.out.println("entries:" + entries);}}