简介
Lettuce是一个高性能基于Java编写的Redis驱动框架,底层集成了Project Reactor提供天然的反应式编程,通信框架集成了Netty使用了非阻塞IO,5.x版本之后融合了JDK1.8的异步编程特性,在保证高性能的同时提供了十分丰富易用的API,5.1版本的新特性如下:
- 支持Redis的新增命令ZPOPMIN, ZPOPMAX, BZPOPMIN, BZPOPMAX。
- 支持通过Brave模块跟踪Redis命令执行。
- 支持Redis Streams。
- 支持异步的主从连接。
- 支持异步连接池。
- 新增命令最多执行一次模式(禁止自动重连)。
- 全局命令超时设置(对异步和反应式命令也有效)。
…
注意一点:Redis的版本至少需要2.6,当然越高越好,API的兼容性比较强大。
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封装到了不同的类型中:
整合SpringBoot
在SpringBoot的某个版本中,spring-boot-starter-data-redis已经默认支持Lettuce(在此之前是Jedis)
添加核心依赖
<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>
配置文件
server:
port: 8080
spring:
application:
name: redis-lettuce
redis:
database: 0 #Redis索引0~15,默认为0
host: ip
port: 6379
password: #密码(默认为空)
lettuce: # 这里标明使用lettuce配置
pool:
max-active: 8 #连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms #连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 5 #连接池中的最大空闲连接
min-idle: 0 #连接池中的最小空闲连接
timeout: 10000ms #连接超时时间(毫秒)
测试代码
package com.issavior.lettuce;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@Slf4j
@SpringBootTest
class LettuceJUnitTest {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void test() {
redisTemplate.opsForValue().set("lettuce:test:key1", "hello,redis!");
log.info("已经存入redis");
String str = redisTemplate.opsForValue().get("lettuce:test:key1");
System.out.println(str);
}
}
测试结果
2022-05-29 00:49:19.071 INFO 5971 --- [ main] com.issavior.lettuce.LettuceJUnitTest : 已经存入redis
hello,redis!