因为每次 await redis.set() 都触发独立网络往返,100次写入需100次rtt;而pipeline通过打包命令为单次往返,省去99%延迟,但需显式调用async with pipe:及await pipe.execute(),且建议每批≤500条以防超时或内存溢出。

为什么直接用 await redis.set() 批量写入很慢?
因为每次 await redis.set() 都是一次独立的网络往返,哪怕只写 100 个 key,也要发 100 次命令。Redis 本身支持管道(pipeline),但原生 aioredis(v2)或 redis-py(v4+ 异步客户端)的默认异步接口不自动合并请求——你得显式调用管道对象。
常见错误是误以为 await redis.pipeline() 返回的是可 await 的对象,其实它返回的是一个未执行的管道实例;或者在 asyncio 环境里混用同步管道(redis.Redis().pipeline()),导致事件循环卡死。
- 同步管道不能在协程里直接调用
execute(),会阻塞整个 event loop -
aioredisv1 已废弃,v2 的Redis实例不带pipeline()方法,必须用create_pipeline() -
redis-pyv4.3+ 的异步客户端才真正支持async with redis.pipeline() as pipe:语法
用 redis-py v4.3+ 的异步 pipeline 写入一批 key
这是目前最简洁、兼容性较好的方式。前提是已安装 redis>=4.3.0 且使用 redis.from_url("redis://...") 创建异步客户端。
关键点:管道必须用 async with 进入,所有命令调用(如 set、expire)返回的是占位符,不立即执行;只有 execute() 或 execute_command() 才真正发包。
import asyncio
import redis.asyncio as redis
<p>async def batch_set_to_redis():
r = redis.from_url("redis://localhost:6379/0")
data = {"user:1": "alice", "user:2": "bob", "user:3": "carol"}</p><pre class="brush:python;toolbar:false;">async with r.pipeline() as pipe:
for key, value in data.items():
pipe.set(key, value)
pipe.expire(key, 3600) # 可选:统一设 TTL
await pipe.execute() # ← 这里才发出单次多命令请求
注意:pipe.set() 不返回结果,也不抛异常;异常只会在 await pipe.execute() 时集中抛出(比如某个 key 是只读的)。如果需要部分失败仍继续,得自己捕获 redis.ResponseError 并检查 results 列表。
大数量写入时要不要分片?
要。Redis 单次 EXEC 命令没有硬性条数限制,但实际受 TCP 包大小、内存碎片、超时配置影响。实测在千级 key 以上,不分片容易触发 redis.exceptions.ConnectionError: Error while reading from socket 或服务端 maxmemory 拒绝。
- 保守建议单管道不超过 500 条命令(含
SET+EXPIRE等) - 用
itertools.batched()(Python 3.12+)或手动切片,例如[data[i:i+500] for i in range(0, len(data), 500)] - 分片后用
asyncio.gather(*[batch_set_chunk(chunk) for chunk in chunks])并行提交,但别无脑开 100 个并发——Redis 是单线程,过多并发反而增加排队延迟
遇到 Connection closed by server 或 TimeoutError 怎么调?
不是代码写错了,大概率是连接池或超时配置没对上。异步客户端默认连接池很小(minsize=1, maxsize=10),而管道批量操作可能短暂占用多个连接(尤其分片并行时)。
必须显式配置连接池和超时:
r = redis.Redis(
connection_pool=redis.ConnectionPool(
host="localhost",
port=6379,
db=0,
minsize=5,
maxsize=20,
decode_responses=False,
),
socket_connect_timeout=5,
socket_timeout=10,
)
另外,socket_timeout 必须大于单次 execute() 的预期耗时——500 个 key 的 pipeline 在局域网通常
真正容易被忽略的是:Redis 服务端自身的 timeout 配置(单位秒),默认是 0(永不过期),但某些云 Redis(如阿里云 Tair)会强制设为 30,此时客户端 socket_timeout 必须小于它,否则连接可能被服务端主动断开。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











