Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4997208
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2013-11-01 14:27:55

redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。
在一次分享中提到了Redis的长短链接的问题,引发了对redis-py的连接池机制的讨论。

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

     
  1.  352 #### COMMAND EXECUTION AND PROTOCOL PARSING ####

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

  3.  354 "Execute a command and return a parsed response"

  4.  355 pool = self.connection_pool

  5.  356 command_name = args[0]

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

  7.  358 try:

  8.  359 connection.send_command(*args)

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

  10.  361 except ConnectionError:

  11.  362 connection.disconnect()

  12.  363 connection.send_command(*args)

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

  14.  365 finally:

  15.  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) 可以手工配置最大的连接池数量。


原文:http://bofang.iteye.com/blog/1724394

 

阅读(3422) | 评论(0) | 转发(0) |
0

上一篇:redis-py的使用

下一篇:gen_event讲解

给主人留下些什么吧!~~