在Python中如何关闭Redis连接?
https://github.com/andymccurdy/redis-py
我知道在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
Ruby:
require "redis"
redis = Redis.new
redis.set("mykey", "hello world")
puts redis.get("mykey")
redis.quit()
4 个回答
6
当你使用连接池(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)
最后,不管你做什么,每个连接都会被释放回连接池,然后可以分配给其他客户端使用。
10
使用Redis连接池。你不需要手动关闭它。
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)
这样可以提高效率。
18
StrictRedis并不自己处理连接的细节,而是使用一个连接池。这个连接池可以通过StrictRedis实例的一个属性来访问,叫做S.connection_pool
。连接池对象有一个disconnect
方法,可以在必要时强制立即断开池中所有的连接。不过,当你的StrictRedis对象不再被使用时,池中的每个连接都会自动清理,不需要你去操心(具体可以参考redis/connection.py的392-396行)。
42
你只需要使用 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)
不过如我之前所说,99.9%的情况下,使用 redis.Redis
是最好的选择。