Spring Boot:Lettuce 原生 API 与 RedisTemplate 对比

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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值