Redis 从入门到精通(十):管道技术

张开发
2026/4/12 4:18:09 15 分钟阅读

分享文章

Redis 从入门到精通(十):管道技术
系列导读本篇将深入讲解 Redis 管道技术大幅提升批量操作性能。文章目录一、管道技术原理1.1 传统请求模式1.2 管道模式二、管道使用方式2.1 命令行管道2.2 Python 管道2.3 Java 管道三、性能对比3.1 测试代码3.2 性能对比四、最佳实践4.1 适用场景4.2 注意事项总结一、管道技术原理1.1 传统请求模式客户端 服务端 │ │ │──── 请求1 ─────────►│ │◄──── 响应1 ─────────│ │ │ │──── 请求2 ─────────►│ │◄──── 响应2 ─────────│ │ │ │──── 请求3 ─────────►│ │◄──── 响应3 ─────────│ 每次请求都需要等待响应RTT开销1.2 管道模式客户端 服务端 │ │ │──── 请求1 ─────────►│ │──── 请求2 ─────────►│ │──── 请求3 ─────────►│ │ │ │◄──── 响应1 ─────────│ │◄──── 响应2 ─────────│ │◄──── 响应3 ─────────│ 批量发送批量接收减少RTT二、管道使用方式2.1 命令行管道# 使用管道批量执行(echo-enPING\r\nSET key1 value1\r\nGET key1\r\n;sleep1)|nclocalhost6379# 使用redis-cli --pipecatcommands.txt|redis-cli--pipe2.2 Python 管道importredis rredis.Redis(hostlocalhost,port6379)# 使用管道piper.pipeline()# 批量操作pipe.set(key1,value1)pipe.set(key2,value2)pipe.set(key3,value3)pipe.get(key1)# 执行resultspipe.execute()print(results)2.3 Java 管道JedisjedisnewJedis(localhost);Pipelinepipelinejedis.pipelined();pipeline.set(key1,value1);pipeline.set(key2,value2);pipeline.get(key1);ListObjectresultspipeline.syncAndReturnAll();三、性能对比3.1 测试代码importredisimporttime rredis.Redis()# 无管道starttime.time()foriinrange(10000):r.set(fkey{i},fvalue{i})print(f无管道:{time.time()-start:.2f}秒)# 有管道starttime.time()piper.pipeline()foriinrange(10000):pipe.set(fkey{i},fvalue{i})pipe.execute()print(f有管道:{time.time()-start:.2f}秒)3.2 性能对比操作无管道有管道提升10000次SET1.18秒0.25秒5倍100000次SET11.8秒2.5秒5倍四、最佳实践4.1 适用场景✅ 批量写入数据 ✅ 批量读取数据 ✅ 数据迁移 ✅ 初始化数据4.2 注意事项# 控制管道大小避免内存溢出defbatch_insert(data,batch_size1000):piper.pipeline()fori,iteminenumerate(data):pipe.set(item[key],item[value])if(i1)%batch_size0:pipe.execute()piper.pipeline()pipe.execute()总结本文我们学习了✅管道原理减少RTT开销✅使用方式命令行、Python、Java✅性能提升5倍以上性能提升✅最佳实践控制批次大小下篇预告Redis 从入门到精通十一持久化配置作者刘~浪地球系列Redis 从入门到精通十更新时间2026-04-06

更多文章