展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > 使用Lettuce连接和操作Redis的步骤和方法

使用Lettuce连接和操作Redis的步骤和方法

Redis Assistant
Redis Assistant

Redis Assistant 是一款为Redis设计的高效可视化管理与监控工具,提供多种操作模式,高效处理服务器数据。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。

¥19
Windows/macOS/Linux 2026-08-22
正版软件 Windows macOS软件 Linux 数据库管理工具
立即下载

一、摘要Lettuce是Redis的一款高级Java客户端,与Jedis并列成为最热门的客户端之一,目前已成为SpringBoot2.0版本默认的redis客户端。相比老牌Jedis,Lettuce属于后起之秀,不仅功能丰富,而且提供了很多新的功能特性,比如异步操作、响应式编程等等,同时还解决了Jedis中线程不安全的问题。二、Lettuce2.1、基本使用首先,创建一个maven项目,引入lettuce-core包,就可以使用了。io.lettucelettuce-core5.3.1.RELEASE使用

本文目录

    一、摘要

    Lettuce 是 Redis 的一款高级 Java 客户端,与 Jedis 并列成为最热门的客户端之一,目前已成为 SpringBoot 2.0 版本默认的 redis 客户端。

    相比老牌 Jedis,Lettuce 属于后起之秀,不仅功能丰富,而且提供了很多新的功能特性,比如异步操作、响应式编程等等,同时还解决了 Jedis 中线程不安全的问题。

    二、Lettuce

    2.1、基本使用

    首先,创建一个 maven 项目,引入lettuce-core包,就可以使用了。

    
      io.lettuce
      lettuce-core
      5.3.1.RELEASE
    

    使用 lettuce 连接 redis,测试是否能正常联通!

    public class LettuceMain {
    
        public static void main(String[] args) {
            RedisURI redisUri = RedisURI.builder()
                    .withHost("127.0.0.1")
                    .withPort(6379)
                    .withPassword("111111")
                    .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                    .build();
            RedisClient redisClient = RedisClient.create(redisUri);
            StatefulRedisConnection connection = redisClient.connect();
            RedisCommands commands = connection.sync();
            System.out.println(commands.ping());
            connection.close();
            redisClient.shutdown();
        }
    }

    2.2、同步操作

    基本上只要是 Jedis 支持的同步命令操作,Lettuce 都支持。

    下面,我们以同步操作字符串为例,Lettuce 的 api 操作如下!

    public class LettuceSyncMain {
    
        public static void main(String[] args) {
            RedisURI redisUri = RedisURI.builder()
                    .withHost("127.0.0.1").withPort(6379).withPassword("111111")
                    .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                    .build();
            RedisClient redisClient = RedisClient.create(redisUri);
            StatefulRedisConnection connection = redisClient.connect();
            //获取同步操作命令工具
            RedisCommands commands = connection.sync();
    
            System.out.println("清空数据:"+commands.flushdb());
            System.out.println("判断某个键是否存在:"+commands.exists("username"));
            System.out.println("新增<'username','xmr'>的键值对:"+commands.set("username", "xmr"));
            System.out.println("新增<'password','password'>的键值对:"+commands.set("password", "123"));
            System.out.println("获取<'password'>键的值:"+commands.get("password"));
            System.out.println("系统中所有的键如下:" + commands.keys("*"));
            System.out.println("删除键password:"+commands.del("password"));
            System.out.println("判断键password是否存在:"+commands.exists("password"));
            System.out.println("设置键username的过期时间为5s:"+commands.expire("username", 5L));
            System.out.println("查看键username的剩余生存时间:"+commands.ttl("username"));
            System.out.println("移除键username的生存时间:"+commands.persist("username"));
            System.out.println("查看键username的剩余生存时间:"+commands.ttl("username"));
            System.out.println("查看键username所存储的值的类型:"+commands.type("username"));
    
            connection.close();
            redisClient.shutdown();
        }
    }

    2.3、异步操作

    除此之外,Lettuce 还支持异步操作,将上面的操作改成异步处理,结果如下!

    public class LettuceASyncMain {
    
        public static void main(String[] args) throws Exception {
            RedisURI redisUri = RedisURI.builder()
                    .withHost("127.0.0.1").withPort(6379).withPassword("111111")
                    .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                    .build();
            RedisClient redisClient = RedisClient.create(redisUri);
            StatefulRedisConnection connection = redisClient.connect();
            //获取异步操作命令工具
            RedisAsyncCommands commands = connection.async();
    
            System.out.println("清空数据:"+commands.flushdb().get());
            System.out.println("判断某个键是否存在:"+commands.exists("username").get());
            System.out.println("新增<'username','xmr'>的键值对:"+commands.set("username", "xmr").get());
            System.out.println("新增<'password','password'>的键值对:"+commands.set("password", "123").get());
            System.out.println("获取<'password'>键的值:"+commands.get("password").get());
            System.out.println("系统中所有的键如下:" + commands.keys("*").get());
            System.out.println("删除键password:"+commands.del("password").get());
            System.out.println("判断键password是否存在:"+commands.exists("password").get());
            System.out.println("设置键username的过期时间为5s:"+commands.expire("username", 5L).get());
            System.out.println("查看键username的剩余生存时间:"+commands.ttl("username").get());
            System.out.println("移除键username的生存时间:"+commands.persist("username").get());
            System.out.println("查看键username的剩余生存时间:"+commands.ttl("username").get());
            System.out.println("查看键username所存储的值的类型:"+commands.type("username").get());
    
            connection.close();
            redisClient.shutdown();
        }
    }

    2.4、响应式编程

    Lettuce 除了支持异步编程以外,还支持响应式编程,Lettuce 引入的响应式编程框架是Project Reactor,如果没有响应式编程经验可以先自行了解一下。

    响应式编程使用案例如下:

    public class LettuceMain {
    
        public static void main(String[] args) throws Exception {
            RedisURI redisUri = RedisURI.builder()
                    .withHost("127.0.0.1").withPort(6379).withPassword("111111")
                    .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                    .build();
            RedisClient redisClient = RedisClient.create(redisUri);
            StatefulRedisConnection connection = redisClient.connect();
            //获取响应式API操作命令工具
            RedisReactiveCommands commands = connection.reactive();
    
            Mono setc = commands.set("name", "mayun");
            System.out.println(setc.block());
            Mono getc = commands.get("name");
            getc.subscribe(System.out::println);
            Flux keys = commands.keys("*");
            keys.subscribe(System.out::println);
    
            //开启一个事务,先把count设置为1,再将count自增1
            commands.multi().doOnSuccess(r -> {
                commands.set("count", "1").doOnNext(value -> System.out.println("count1:" +  value)).subscribe();
                commands.incr("count").doOnNext(value -> System.out.println("count2:" +  value)).subscribe();
            }).flatMap(s -> commands.exec())
                    .doOnNext(transactionResult -> System.out.println("transactionResult:" + transactionResult.wasDiscarded())).subscribe();
    
            Thread.sleep(1000 * 5);
            connection.close();
            redisClient.shutdown();
        }
    }

    2.5、发布和订阅

    Lettuce 还支持 redis 的消息发布和订阅,具体实现案例如下:

    public class LettuceReactiveMain1 {
    
        public static void main(String[] args) throws Exception {
            RedisURI redisUri = RedisURI.builder()
                    .withHost("127.0.0.1").withPort(6379).withPassword("111111")
                    .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                    .build();
            RedisClient redisClient = RedisClient.create(redisUri);
            //获取发布订阅操作命令工具
            StatefulRedisPubSubConnection pubsubConn = redisClient.connectPubSub();
            pubsubConn.addListener(new RedisPubSubListener() {
                @Override
                public void unsubscribed(String channel, long count) {
                    System.out.println("[unsubscribed]" + channel);
                }
                @Override
                public void subscribed(String channel, long count) {
                    System.out.println("[subscribed]" + channel);
                }
                @Override
                public void punsubscribed(String pattern, long count) {
                    System.out.println("[punsubscribed]" + pattern);
                }
                @Override
                public void psubscribed(String pattern, long count) {
                    System.out.println("[psubscribed]" + pattern);
                }
                @Override
                public void message(String pattern, String channel, String message) {
                    System.out.println("[message]" + pattern + " -> " + channel + " -> " + message);
                }
                @Override
                public void message(String channel, String message) {
                    System.out.println("[message]" + channel + " -> " + message);
                }
            });
            RedisPubSubAsyncCommands pubsubCmd = pubsubConn.async();
            pubsubCmd.psubscribe("CH");
            pubsubCmd.psubscribe("CH2");
            pubsubCmd.unsubscribe("CH");
    
            Thread.sleep(100 * 5);
            pubsubConn.close();
            redisClient.shutdown();
        }
    }

    2.6、客户端资源与参数配置

    Lettuce 客户端的通信框架集成了 Netty 的非阻塞 IO 操作,客户端资源的设置与 Lettuce 的性能、并发和事件处理紧密相关,如果不是特别熟悉客户端参数配置,不建议在没有经验的前提下凭直觉修改默认值,保持默认配置就行。

    非集群环境下,具体的配置案例如下:

    public class LettuceMain {
    
        public static void main(String[] args) throws Exception {
            ClientResources resources = DefaultClientResources.builder()
                    .ioThreadPoolSize(4) //I/O线程数
                    .computationThreadPoolSize(4) //任务线程数
                    .build();
            RedisURI redisUri = RedisURI.builder()
                    .withHost("127.0.0.1").withPort(6379).withPassword("111111")
                    .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                    .build();
            ClientOptions options = ClientOptions.builder()
                    .autoReconnect(true)//是否自动重连
                    .pingBeforeActivateConnection(true)//连接激活之前是否执行PING命令
                    .build();
            RedisClient client = RedisClient.create(resources, redisUri);
            client.setOptions(options);
            StatefulRedisConnection connection = client.connect();
            RedisCommands commands = connection.sync();
            commands.set("name", "关羽");
            System.out.println(commands.get("name"));
    
            connection.close();
            client.shutdown();
            resources.shutdown();
        }
    }

    集群环境下,具体的配置案例如下:

    public class LettuceMain {
    
        public static void main(String[] args) throws Exception {
            ClientResources resources = DefaultClientResources.builder()
                    .ioThreadPoolSize(4) //I/O线程数
                    .computationThreadPoolSize(4) //任务线程数
                    .build();
            RedisURI redisUri = RedisURI.builder()
                    .withHost("127.0.0.1").withPort(6379).withPassword("111111")
                    .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                    .build();
            ClusterClientOptions options = ClusterClientOptions.builder()
                    .autoReconnect(true)//是否自动重连
                    .pingBeforeActivateConnection(true)//连接激活之前是否执行PING命令
                    .validateClusterNodeMembership(true)//是否校验集群节点的成员关系
                    .build();
            RedisClusterClient client = RedisClusterClient.create(resources, redisUri);
            client.setOptions(options);
            StatefulRedisClusterConnection connection = client.connect();
            RedisAdvancedClusterCommands commands = connection.sync();
            commands.set("name", "张飞");
            System.out.println(commands.get("name"));
    
            connection.close();
            client.shutdown();
            resources.shutdown();
        }
    }

    2.7、线程池配置

    Lettuce 连接设计的时候,就是线程安全的,所以一个连接可以被多个线程共享,同时 lettuce 连接默认是自动重连的,使用单连接基本可以满足业务需求,大多数情况下不需要配置连接池,多连接并不会给操作带来性能上的提升。

    但在某些特殊场景下,比如事物操作,使用连接池会是一个比较好的方案,那么如何配置线程池呢?

    public class LettuceMain {
    
        public static void main(String[] args) throws Exception {
            RedisURI redisUri = RedisURI.builder()
                    .withHost("127.0.0.1")
                    .withPort(6379)
                    .withPassword("111111")
                    .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                    .build();
            RedisClient client = RedisClient.create(redisUri);
            //连接池配置
            GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
            poolConfig.setMaxIdle(2);
    
            GenericObjectPool> pool = ConnectionPoolSupport.createGenericObjectPool(client::connect, poolConfig);
            StatefulRedisConnection connection = pool.borrowObject();
            RedisCommands commands = connection.sync();
            commands.set("name", "张飞");
            System.out.println(commands.get("name"));
    
            connection.close();
            pool.close();
            client.shutdown();
        }
    }

    2.8、主从模式配置

    redis 一般采用主从复制模式,搭建高可用的架构,简单的说就一个主节点,多个从节点,自动从主节点同步最新数据。

    Lettuce 支持自动发现主从模式下的节点信息,然后保存到本地,具体配置如下:

    public class LettuceMain {
    
        public static void main(String[] args) throws Exception {
            //这里只需要配置一个节点的连接信息,不一定需要是主节点的信息,从节点也可以;可以自动发现主从节点
            RedisURI uri = RedisURI.builder().withHost("192.168.31.111").withPort(6379).withPassword("123456").build();
            RedisClient client = RedisClient.create(uri);
            StatefulRedisMasterReplicaConnection connection = MasterReplica.connect(client, StringCodec.UTF8, uri);
            //从节点读取数据
            connection.setReadFrom(ReadFrom.REPLICA);
    
            RedisCommands commands = connection.sync();
            commands.set("name", "张飞");
            System.out.println(commands.get("name"));
    
            connection.close();
            client.shutdown();
        }
    }

    当然我们也可以手动指定集群节点来加载,具体配置如下:

    public class LettuceMain {
    
        public static void main(String[] args) throws Exception {
            //集群节点
            List uris = new ArrayList();
            uris.add(RedisURI.builder().withHost("192.168.31.111").withPort(6379).withPassword("111111").build());
            uris.add(RedisURI.builder().withHost("192.168.31.112").withPort(6379).withPassword("111111").build());
            uris.add(RedisURI.builder().withHost("192.168.31.113").withPort(6379).withPassword("111111").build());
    
            RedisClient client = RedisClient.create();
            StatefulRedisMasterReplicaConnection connection = MasterReplica.connect(client, StringCodec.UTF8, uris);
            //从节点读取数据
            connection.setReadFrom(ReadFrom.REPLICA);
    
            RedisCommands commands = connection.sync();
            commands.set("name", "张飞");
            System.out.println(commands.get("name"));
    
            connection.close();
            client.shutdown();
        }
    }

    2.9、哨兵模式配置

    哨兵模式,也是 redis 实现服务高可用的一大亮点,具体配置实现如下:

    public class LettuceMain {
    
        public static void main(String[] args) throws Exception {
            //集群节点
            List uris = new ArrayList();
            uris.add(RedisURI.builder().withSentinel("192.168.31.111", 26379).withSentinelMasterId("mymaster").withPassword("123456").build());
            uris.add(RedisURI.builder().withSentinel("192.168.31.112", 26379).withSentinelMasterId("mymaster").withPassword("123456").build());
            uris.add(RedisURI.builder().withSentinel("192.168.31.113", 26379).withSentinelMasterId("mymaster").withPassword("123456").build());
    
            RedisClient client = RedisClient.create();
            StatefulRedisMasterReplicaConnection connection = MasterReplica.connect(client, StringCodec.UTF8, uris);
            //从节点读取数据
            connection.setReadFrom(ReadFrom.REPLICA);
    
            RedisCommands commands = connection.sync();
            commands.set("name", "赵云");
            System.out.println(commands.get("name"));
    
            connection.close();
            client.shutdown();
        }
    }

    2.10、Cluster 集群模式配置

    Cluster 集群模式,是之后推出的一种高可用的架构模型,主要是采用分片方式来存储数据,具体配置如下:

    public class LettuceReactiveMain4 {
    
        public static void main(String[] args) throws Exception {
            Set uris = new HashSet<>();
            uris.add(RedisURI.builder().withHost("192.168.31.111").withPort(7000).withPassword("123456").build());
            uris.add(RedisURI.builder().withHost("192.168.31.112").withPort(7000).withPassword("123456").build());
            uris.add(RedisURI.builder().withHost("192.168.31.113").withPort(7000).withPassword("123456").build());
            uris.add(RedisURI.builder().withHost("192.168.31.114").withPort(7000).withPassword("123456").build());
            uris.add(RedisURI.builder().withHost("192.168.31.115").withPort(7000).withPassword("123456").build());
            uris.add(RedisURI.builder().withHost("192.168.31.116").withPort(7001).withPassword("123456").build());
    
            RedisClusterClient client = RedisClusterClient.create(uris);
            StatefulRedisClusterConnection connection = client.connect();
            RedisAdvancedClusterCommands commands = connection.sync();
            commands.set("name", "关羽");
            System.out.println(commands.get("name"));
    
            //选择从节点,只读
            NodeSelection replicas = commands.replicas();
            NodeSelectionCommands nodeSelectionCommands = replicas.commands();
            Executions> keys = nodeSelectionCommands.keys("*");
            keys.forEach(key -> System.out.println(key));
    
            connection.close();
            client.shutdown();
        }
    }
    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    Aperty macOS版
    Aperty macOS版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw macOS版
    AionClaw macOS版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy macOS版
    Loomy macOS版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirBuddy 3 macOS版
    AirBuddy 3 macOS版

    AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

    AirServer macOS版
    AirServer macOS版

    AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

    AnyDesk macOS版
    AnyDesk macOS版

    AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    讯飞绘文 网页版
    讯飞绘文 网页版

    讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

    Maya(Autodesk Maya) Windows版
    Maya(Autodesk Maya) Windows版

    Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

    Aperty Windows版
    Aperty Windows版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw Windows版
    AionClaw Windows版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy Windows版
    Loomy Windows版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirServer Windows版
    AirServer Windows版

    AirServer Windows版可把电脑变成AirPlay、Google Cast和Miracast无线投屏接收端,适合会议演示、课堂教学及家庭大屏分享。发送设备通常无需另装客户端,并可同时接收和智能排列多个镜像会话。

    即将离开本站
    您即将前往第三方网站,请确认是否继续?