假设我在python服务器上打开了10个不同的redis连接,如下所示:
import redis
conn1 = redis.Redis(host=aaaa)
conn2 = redis.Redis(host=bbbb)
conn3 = redis.Redis(host=cccc)
...
conn10 = redis.Redis(host=jjjj)redis-py是如何在幕后运行的,我的服务器会因为每次额外的redis.Redis()调用而变慢吗?
发布于 2021-08-17 09:22:54
redis-py使用ConnectionPool管理连接,并且它不预先填充连接池。只需发送命令即可创建连接。
下面的源代码足以帮助理解这个过程。如果你想深入挖掘,请阅读redis-py的源代码。
class Redis:
def set(self, name, value,
ex=None, px=None, nx=False, xx=False, keepttl=False, get=False):
...
return self.execute_command('SET', *pieces, **options)
def execute_command(self, *args, **options):
...
conn = self.connection or pool.get_connection(command_name, **options)
try:
conn.send_command(*args)
return self.parse_response(conn, command_name, **options)
...ConnectionPool.get_connection()是conn创建的地方。实际上,它是正在创建的底层套接字。
class ConnectionPool:
def get_connection(self, command_name, *keys, **options):
...
try:
# ensure this connection is connected to Redis
connection.connect()
...
class Connection:
...
def _connect(self):
"Create a TCP socket connection"
# we want to mimic what socket.create_connection does to support
# ipv4/ipv6, but we want to set options prior to calling
# socket.connect()
err = None
for res in socket.getaddrinfo(self.host, self.port, self.socket_type,
socket.SOCK_STREAM):
family, socktype, proto, canonname, socket_address = res
sock = None
try:
sock = socket.socket(family, socktype, proto)
...https://stackoverflow.com/questions/66231465
复制相似问题