- 本章:将展示SpringBoot集成Redis三种客户端的配置要点和常见应用示例;
- 下章:自行实现一个方法级的缓存注解,简化版的Cacheable,使初学者加深对Spring缓存框架的理解。
一、Lettuce客户端
Lettuce 是一种可扩展的、线程安全的 Redis 高级客户端。
从 Spring Boot 2.x 开始, Lettuce 已取代 Jedis 成为SpringBoot 默认的 Redis 客户端。
- 相比于 Jedis,Lettuce更加全面,并且解决了 Jedis 客户端实例存在非线程安全的问题
- 支持同步编程,异步编程,响应式编程,自动重新连接,主从模式,集群模块,哨兵模式,管道和编码器等等高级的 Redis 特性
- Lettuce 底层基于 Netty 框架的事件驱动与 redis 通信,采用了非阻塞的 I/O 操作,可异步调用,相比 Jedis,性能高
- Lettuce 的 API 是线程安全的,如果不是执行阻塞和事务操作,如 BLPOP 和MULTI/EXEC 等命令,多个线程就可以共享一个连接,性能方面不会衰减。
1.1 pom.xml引入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!-- redis 缓存操作 默认使用 Lettuce 客户端-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- pool 对象池 Lettuce客户端依赖的插件-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.34</version>
</dependency>
<!-- 方便等会写单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
1.2 application.yml
配置redis服务器配置
spring:
redis:
# 地址
host: localhost
# 端口,默认为6379
port: 6379
# 数据库索引
database: 0
# 密码
password: 123456
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
1.3 redis缓存应用
UserService.java
@Service
public class UserService {
//由于引入redis-starter包,spring已经完成了RedisTemplate 对象创建,什么都不用做就可以直接使用了。
@Autowired
RedisTemplate redisTemplate;
/**
* 最简单的使用,通过key-value方式存取变量;
* @param username
* @return
*/
public Object getUserInfo(String username) {
//通过用户名从缓存获取用户信息,如果没有即新建并存缓存起来;
if (redisTemplate.opsForValue().get(username) == null) {
System.out.println("未获取到缓存,新建用户信息.............");
Map<String, Object> user = new HashMap<>();
user