https://github.com/andymccurdy/redis-py
我知道在ruby中我们使用quit()方法.我在这里找不到任何关于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
Run Code Online (Sandbox Code Playgroud)
红宝石
require "redis"
redis = Redis.new
redis.set("mykey", "hello world")
puts redis.get("mykey")
redis.quit()
Run Code Online (Sandbox Code Playgroud)
man*_*art 25
只是用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
Run Code Online (Sandbox Code Playgroud)
用法示例:
response = execute_low_level(
'HGET', 'redis:key', 'hash:key', host='localhost', port=6379)
Run Code Online (Sandbox Code Playgroud)
但正如我之前所说,redis.Redis99.9%的案例是可行的.
sir*_*ark 13
StrictRedis本身不实现连接语义,而是使用连接池,该连接池可用作StrictRedis实例的属性:S.connection_pool.connection_pool对象有一个disconnect强制立即断开池中所有连接的方法,但是当您的StrictRedis对象超出范围时,池中的各个连接都会自行清理而无需您的干预(请参阅redis/connection.py) :392-396)
使用Redis连接池。您不需要明确关闭它。
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)
Run Code Online (Sandbox Code Playgroud)
并且可以提高效率。
小智 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)
Run Code Online (Sandbox Code Playgroud)
最后,无论您做什么,每个连接都会释放到池中,并将分配给其他客户端。
| 归档时间: |
|
| 查看次数: |
23484 次 |
| 最近记录: |