关于Redis的Python客户端的连接池问题

关于Redis的Python客户端的连接池问题



在一次分享中提到了Redis的长短链接的问题,引发了对redis-py的连接池机制的讨论。


通过源码发现,每创建一个Redis实例都会构造出一个ConnectionPool,每一次访问redis都会从这个连接池得到一个连接,访问完成之后,会把该连接放回连接池,下面是发送命令访问redis的execute_command方法实现:


Python代码 收藏代码
352 #### COMMAND EXECUTION AND PROTOCOL PARSING ####

353 def execute_command(self, *args, **options):

354 "Execute a command and return a parsed response"

355 pool = self.connection_pool

356 command_name = args[0]

357 connection = pool.get_connection(command_name, **options)

358 try:

359 connection.send_command(*args)

360 return self.parse_response(connection, command_name, **options)

361 except ConnectionError:

362 connection.disconnect()

363 connection.send_command(*args)

364 return self.parse_response(connection, command_name, **options)

365 finally:

366 pool.release(connection)

当然,也可以构造一个ConnectionPool,在创建Redis实例时,可以将该ConnectionPool传入,那么后续的操作会从给定的ConnectionPool获得连接。

redis-py的作者在文档中也有详细说明:

Connection Pools

Behind the scenes, redis-py uses a connection pool to manage connections to a Redis server. By default, each Redis instance you create will in turn create its own connection pool. You can override this behavior and use an existing connection pool by passing an already created connection pool instance to the connection_pool argument of the Redis class. You may choose to do this in order to implement client side sharding or have finer grain control of how connections are managed.

>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
>>> r = redis.Redis(connection_pool=pool)


关于redis-server的最大客户端数量问题

redis的文档这样说:

# Set the max number of connected clients at the same time. By default there
# is no limit, and it's up to the number of file descriptors the Redis process
# is able to open. The special value '0' means no limits.
# Once the limit is reached Redis will close all the new connections sending
# an error 'max number of clients reached'.
#
# maxclients 128

1) redis默认没有设置最大的连接客户端数量,这个数量取决于redis进程能够打开的文件句柄数量。

2) 可以手工配置最大的连接池数量。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值