Redis 管道技术

用 Pipeline 把多条命令打包,减少网络往返。

Beginner
Key PointsPipeline 不保证原子(仍是逐条执行),但把 N 次 RTT 压成 1 次,吞吐飙升。

原理与用法

Python
import redis
r = redis.Redis()
# 不用管道:每条命令一次往返
# 用管道:一次性发一批
pipe = r.pipeline()
for i in range(1000):
    pipe.set(f'k:{i}', i)
pipe.execute()        # 只一次网络往返
Output
[True, True, ...]   # 1000 个结果一次返回
Pipeline differs from MULTI: it only batches the network send, commands still run one by one and may interleave with others; MULTI guarantees isolation. For bulk writes (cache warm-up) prefer Pipeline.

Friends & Partners