spring-data-redis是什么
官方地址:https://spring.io/projects/spring-data-redis#support
提供了对RedisTemplate统一的api来操作数据库
支持Redis的发布订阅
支持Redis的哨兵和Redis集群
支持基于Lettuce的响应是编程
支持基于JDK,JSON,字符串,spring对象的数据序列化以及反序列化
支持基于Redis的Jdkcollection实现
spring-data-redis是spring官方提供的一个可以操作redis的框架
spring-data-redis整合了jedis和lettuce
spring-data-redis使我们在使用使用springboot框架可以更好的去使用redis
lettuce是什么
lettuce是一个线程安全的redis客户端。提供同步,异步和reactive(?)的 APIs.。如果可以避开阻塞和事务型的操作比如BLPOP 和MULTI/EXEC,多个线程可以分享同一个连接。多个连接被NIO框架netty有效的管理。
lettuce是基于netty实现的,支持同步,异步,和响应式编程方式,并且是线程安全的,支持Redis的哨兵模式,集群和管道模式。
基本使用
springDataRedis中提供了RedisTemplate工具类。其中封装了各种对redis的操作,并且将不同的api封装到不同的类型中
![](https://i-blog.csdnimg.cn/blog_migrate/cfb2871a548114895014dd02fff60fa9.png)
实际操作
导入maven依赖
<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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
编写redis数据库配置
spring.redis.host=172.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-wait=100ms
操作
private static final ObjectMapper mapper=new ObjectMapper(); //序列化工具
@Autowired
private StringRedisTemplate redisTemplate;
User user = new User("小华", "玩");
try {
//序列化成字符串
String s = mapper.writeValueAsString(user);
redisTemplate.opsForValue().set("user",s);
//反序列化成user对象
User user1 = mapper.readValue(redisTemplate.opsForValue().get("user"), User.class);
System.out.println(user1);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
注意点:
序列化成字符串表示将创建的user对象序列化成字符串,然后存进redis中,在读取的时候进行一个反序列化成user对象,保证了redis中保存的都是字符串
spring-data-redis默认使用的是lettuce,如果想要使用jedis就需要引入jedis依赖
![](https://i-blog.csdnimg.cn/blog_migrate/0b95803f48b6b4e1b4ada4262f513227.png)