Redis 管道技术
用 Pipeline 把多条命令打包,减少网络往返。
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.
原理与用法
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 和事务(MULTI/EXEC)不同:Pipeline 只合并网络发送、命令仍逐条执行且可能穿插其它客户端命令;MULTI 才保证隔离。批量写(如预热缓存)首选 Pipeline。