【Aioredis实战总结】如何修改aioredis的最大连接数。
1. 修改 aioredis 连接池参数
在初始化 aioredis.ConnectionPool
时,通过 max_connections
参数显式设置最大连接数。以下为示例代码:
from aioredis import ConnectionPool, Redis
# 创建连接池时指定最大连接数
pool = ConnectionPool.from_url(
"redis://localhost:6379",
max_connections=100, # 自定义最大连接数
decode_responses=True
)
redis_client = Redis(connection_pool=pool)
此处的 max_connections
决定了连接池允许创建的最大连接数。
适用场景:需要精准控制客户端连接数,防止服务端过载或资源浪费。
2. 不设置 max_connections(无限制)
如果省略 max_connections
参数,aioredis 默认会将最大连接数设置为 2^31
(约 21 亿),此时连接数仅受 Redis 服务端限制。示例:
pool = ConnectionPool.from_url("redis://localhost:6379") # 不设置 max_connections
适用场景:高并发场景下需要动态扩展连接数,且服务端资源充足。
3. 调整 Redis 服务端配置
即使客户端允许更多连接,仍需确保 Redis 服务端的 maxclients
参数足够大(默认 10000)。修改方法:
- 修改
redis.conf
文件:maxclients 20000 # 调整服务端最大连接数
- 重启 Redis 服务:
sudo systemctl restart redis-server
注意事项:需根据服务器内存和资源情况合理设置,避免 OOM(内存溢出)。
4. 最佳实践建议
• 平衡连接数与性能:
• 低并发场景:建议设置 max_connections=50~200
,避免闲置连接占用资源。
• 高并发场景:可省略 max_connections
或设置为较大值(如 5000),并配合服务端优化。
• 监控连接使用情况:通过 INFO clients
命令或 Redis 监控工具(如 RedisInsight)实时观察连接数趋势。
• 释放闲置连接:通过 ConnectionPool.disconnect()
或 wait_closed()
方法主动回收不再使用的连接。