系列导读:本篇将深入讲解 Redis 管道技术,大幅提升批量操作性能。
文章目录
一、管道技术原理
1.1 传统请求模式
客户端 服务端
│ │
│──── 请求1 ─────────►│
│◄──── 响应1 ─────────│
│ │
│──── 请求2 ─────────►│
│◄──── 响应2 ─────────│
│ │
│──── 请求3 ─────────►│
│◄──── 响应3 ─────────│
每次请求都需要等待响应(RTT开销)
1.2 管道模式
客户端 服务端
│ │
│──── 请求1 ─────────►│
│──── 请求2 ─────────►│
│──── 请求3 ─────────►│
│ │
│◄──── 响应1 ─────────│
│◄──── 响应2 ─────────│
│◄──── 响应3 ─────────│
批量发送,批量接收,减少RTT
二、管道使用方式
2.1 命令行管道
bash
# 使用管道批量执行
(echo -en "PING\r\nSET key1 value1\r\nGET key1\r\n"; sleep 1) | nc localhost 6379
# 使用redis-cli --pipe
cat commands.txt | redis-cli --pipe
2.2 Python 管道
python
import redis
r = redis.Redis(host='localhost', port=6379)
# 使用管道
pipe = r.pipeline()
# 批量操作
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.set('key3', 'value3')
pipe.get('key1')
# 执行
results = pipe.execute()
print(results)
2.3 Java 管道
java
Jedis jedis = new Jedis("localhost");
Pipeline pipeline = jedis.pipelined();
pipeline.set("key1", "value1");
pipeline.set("key2", "value2");
pipeline.get("key1");
List<Object> results = pipeline.syncAndReturnAll();
三、性能对比
3.1 测试代码
python
import redis
import time
r = redis.Redis()
# 无管道
start = time.time()
for i in range(10000):
r.set(f'key{i}', f'value{i}')
print(f"无管道: {time.time() - start:.2f}秒")
# 有管道
start = time.time()
pipe = r.pipeline()
for i in range(10000):
pipe.set(f'key{i}', f'value{i}')
pipe.execute()
print(f"有管道: {time.time() - start:.2f}秒")
3.2 性能对比
| 操作 | 无管道 | 有管道 | 提升 |
|---|---|---|---|
| 10000次SET | 1.18秒 | 0.25秒 | 5倍 |
| 100000次SET | 11.8秒 | 2.5秒 | 5倍 |
四、最佳实践
4.1 适用场景
✅ 批量写入数据
✅ 批量读取数据
✅ 数据迁移
✅ 初始化数据
4.2 注意事项
python
# 控制管道大小,避免内存溢出
def batch_insert(data, batch_size=1000):
pipe = r.pipeline()
for i, item in enumerate(data):
pipe.set(item['key'], item['value'])
if (i + 1) % batch_size == 0:
pipe.execute()
pipe = r.pipeline()
pipe.execute()
总结
本文我们学习了:
✅ 管道原理 :减少RTT开销
✅ 使用方式 :命令行、Python、Java
✅ 性能提升 :5倍以上性能提升
✅ 最佳实践:控制批次大小
下篇预告 :[Redis 从入门到精通(十一):持久化配置](#Redis 从入门到精通(十一):持久化配置)
作者 :刘~浪地球
系列 :Redis 从入门到精通(十)
更新时间:2026-04-06