Spring Boot 中默认使用 Lettuce 作为 redis-cli 的底层实现。 Lettuce 基于 Netty 实现,提供了相对丰富地同步、异步操作接口。 今天我们将主要对比一下 Lettuce 原生 API 与 spring-boot-data-redis 对其封装后的接口(主要是 RedisTemplate)的使用。
01-Lettuce 原生 API
Lettuce 暴露给用户的接口是非常直观的,针对单实例、集群场景,提供了两个 client 接口:
- io.lettuce.core.RedisClient
- io.lettuce.core.cluster.RedisClusterClient
它们都继承自 io.lettuce.core.AbstractRedisClient,封装了 Netty、ClientOptions(控制 client 行为,例如重连、超时等)和连接过程的实现。
RedisClient 对象的创建是非常简单的:
final RedisURI uri = RedisURI.builder()
.withPassword("redis123")
.withHost("example.samson.self")
.withPort(6379)
.withDatabase(0)
.build();
final RedisClient redisClient = RedisClient.create(uri);
/**
* 上述 uri 对象等价于:
* redis://redis123@example.samson.self:6379/0
*
*/
复制代码
创建了 RedisClient 实例后,可以通过 RedisClient#connect() 方法获得 StatefulRedisConnection 连接对象。 获得连接对象后,可以通过如下接口进行同步、异步及响应式命令的执行:
final StatefulRedisConnection<String, String> connection = client.connect();
final RedisCommands<String, String> sync = connection.sync(); // 同步操作
final RedisAsyncCommands<String, String> async = connection.async(); // 异步操作
final RedisReactiveCommands<String, String> reactive = connection.reactive(); // 响应式操作
复制代码
下文以同步操作为例,演示下通过 Lettuce 原生 API 对 Redis 基本数据结构的操作。
// 字符串
sync.set("str", "str_value");
final String strValue = sync.get("str");
System.out.println("strValue: " + strValue);
// 列表
sync.lpush("list", "value1", "value2");
final Long listLen = sync.llen("list");
final List<String> allList = sync.lrange("list", 0, listLen);
System.out.println("allList: " + String.join(",", allList));
// 集合
sync.sadd("set", "set1", "set2");
final Long setSize = sync.scard("set");
final Set<String> allSet = sync.smembers("set");
System.out.println("setSize: " + setSize);
System.out.println("allSet: " + String.joi