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)
...