python redis连接数_python 里的 redis 连接池的原理

r.set('name','michael')

点击set,查看内部源码:def set(self, name, value, ex=None, px=None, nx=False, xx=False):

...return self.execute_command('SET', *pieces)

在此处发现了方法,execute_command,点击进去查看def execute_command(self, *args, **options):"Execute a command and return a parsed response"pool=self.connection_pool

command_name=args[0]

conn= self.connection or pool.get_connection(command_name, **options)try:

conn.send_command(*args)return self.parse_response(conn, command_name, **options)except(ConnectionError, TimeoutError) as e:

conn.disconnect()if not (conn.retry_on_timeout andisinstance(e, TimeoutError)):raiseconn.send_command(*args)return self.parse_response(conn, command_name, **options)finally:if notself.connection:

pool.release(conn)

找到了conn= self.connection or pool.get_connection(command_name, **options)

因为self.connection初始值为False,所以此处调用了方法 get_connection

点击查看get_connection,def get_connection(self, command_name, *keys, **options):"Get a connection from the pool"self._checkpid()try:

connection=self._available_connections.pop()exceptIndexError:

connection=self.make_connection()

self._in_use_connections.add(connection)

。。。。。。except: #noqa: E722

self.release(connection)raise

returnconnection

如果有有用的连接,获取可用的连接,没有,自己创建一个 make_connection ,点击查看make_connectiondefmake_connection(self):"Create a new connection"

if self._created_connections >=self.max_connections:raise ConnectionError("Too many connections")

self._created_connections+= 1

return self.connection_class(**self.connection_kwargs)

终于,在此处创建了连接!!!

在ConnectionPool的实例中, 有两个list, 依次是_available_connections, _in_use_connections,

分别表示可用的连接集合和正在使用的连接集合, 在上面的get_connection中, 我们可以看到获取连接的过程是:

从可用连接集合尝试获取连接,

如果获取不到, 重新创建连接

将获取到的连接添加到正在使用的连接集合

上面是往_in_use_connections里添加连接的, 这种连接表示正在使用中, 那是什么时候将正在使用的连接放回到可用连接列表中的呢

这个还是在execute_command里, 我们可以看到在执行redis操作时, 在finally部分, 会执行一下

pool.release(connection)

连接池对象调用release方法, 将连接从_in_use_connections 放回 _available_connections, 这样后续的连接获取就能再次使用这个连接了

release 方法如下defrelease(self, connection):"Releases the connection back to the pool"self._checkpid()if connection.pid !=self.pid:returnself._in_use_connections.remove(connection)

self._available_connections.append(connection)

至此, 我们把连接池的管理流程走了一遍, ConnectionPool通过管理可用连接列表(_available_connections) 和 正在使用的连接列表从而实现连接池管理!


版权声明:本文为weixin_34933151原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。