Python异步Redis阻塞式连接池的使用

本文最后更新于:2022年8月31日 晚上

前言

aioredis是Python里比较常用的一款异步Redis库,本文会介绍它提供的两种连接池

ConnectionPool

1
2
3
4
5
6
7
8
redis_pool = aioredis.ConnectionPool.from_url(
"redis://:pwd@127.0.0.1/0",
max_connections=10,
decode_responses=True
)

redis = aioredis.Redis(connection_pool=redis_pool)
print(await redis.get("*"))

这是最基础的创建连接池的方法,这里传入了redis的url,设置最大连接数为10.
但是这种方法有一个问题,如果同时超过10个连接都要使用这个连接池,就会导致错误.

1
aioredis.exceptions.ConnectionError: Too many connections

BlockingConnectionPool

1
2
3
4
5
6
7
8
9
redis_pool = aioredis.BlockingConnectionPool.from_url(
"redis://:pwd@127.0.0.1/0",
max_connections=10,
decode_responses=True,
timeout=None
)

redis = aioredis.Redis(connection_pool=redis_pool)
print(await redis.get("*"))

通过BlockingConnectionPool创建连接池,当同时连接数超过最大值时,会等待‘timeout’秒.
只有等待时间超过’timeout’秒的时候,才会报错.如果设置timeout为None,则会一直保持等待.