在python中,如何关闭连接?
我知道在ruby中我们使用quit()方法。我在这里找不到python的任何内容 python:在python中,如何关闭连接?,python,redis,Python,Redis,我知道在ruby中我们使用quit()方法。我在这里找不到python的任何内容 python: import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) r.set('foo', 'bar') print r.get('foo') #r.close() doesn't work 红宝石 StricRedis本身不实现连接语义,而是使用连接池,该连接池作为StricRedis实例的属性:S.connection\
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
print r.get('foo')
#r.close() doesn't work
红宝石
StricRedis本身不实现连接语义,而是使用连接池,该连接池作为StricRedis实例的属性:
S.connection\u pool
。connection_pool对象有一个disconnect
方法,可以在必要时强制立即断开池中的所有连接,但是当StrictRedis对象超出范围时,池中的各个连接都会在不需要您干预的情况下自行清理(请参阅redis/connection.py:392-396)只需使用redis.redis
。它在引擎盖下使用一个连接池,因此您不必担心在该级别进行管理
如果必须使用低级连接,则需要执行通常由redis.redis
为您执行的响应处理
下面是使用低级连接执行单个命令的示例:
def execute_low_level(command, *args, **kwargs):
connection = redis.Connection(**kwargs)
try:
connection.connect()
connection.send_command(command, *args)
response = connection.read_response()
if command in redis.Redis.RESPONSE_CALLBACKS:
return redis.Redis.RESPONSE_CALLBACKS[command](response)
return response
finally:
del connection
用法示例:
response = execute_low_level(
'HGET', 'redis:key', 'hash:key', host='localhost', port=6379)
但正如我之前所说的,
redis.redis
在99.9%的情况下都是可行的方法。当您使用ConnectionPool时,您不必担心它。查看源代码:
def execute_command(self, *args, **options):
"Execute a command and return a parsed response"
pool = self.connection_pool
command_name = args[0]
connection = pool.get_connection(command_name, **options)
try:
connection.send_command(*args)
return self.parse_response(connection, command_name, **options)
except (ConnectionError, TimeoutError) as e:
connection.disconnect()
if not connection.retry_on_timeout and isinstance(e, TimeoutError):
raise
connection.send_command(*args)
return self.parse_response(connection, command_name, **options)
finally:
pool.release(connection)
最后,无论您做什么,每个连接都将释放到池中,并将分配给其他客户端。使用Redis连接池。您不需要显式地关闭它
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)
而且可以提高效率。看看,
StrictRedis
没有实现close
或quit
方法。我们不关闭连接可以吗,我想我不理解与redis的连接…@不管我看到了r.client\u kill
,但要找出要杀死的客户机,您必须按r.client\u list()
列出它们。检查$netstat | grep6379
我看到,连接进入“关闭”状态。还有r.execute\u命令(“QUIT”)
。但我仍然不确定,如果它真的存在,你要求什么。我们需要杀死它吗?我可以安全地使用StricRedis而不担心连接吗?如果我决定使用Strict,我需要担心连接吗?我阅读了pool.release()
源代码,发现代码如下:python def release(self,connection):“将连接释放回池”self.\u checkpid()如果connection.pid!=self.pid:返回self.\u in.\u使用\u连接。删除(连接)self.\u可用的\u连接。追加(连接)
我的问题是,当self.pid
等于os.getpid
时,或者当进程被终止时,连接自动关闭的程度如何?
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)