python 连接 redis 超时设置_从Python管理与redis的连接

I'm using redis-py in my python application to store simple variables or lists of variables in a Redis database, so I thought it would be better to create a connection to the redis server everytime I need to save or retrieve a variable as this is not done very often and don't want to have a permanent connection that might timeout.

Reading through some basic tutorials I created the connections using the Redis class, but have not found a way to close the connection, as this is the first time I'm using Redis. I'm not sure if I'm using the best approach for managing the connections so I would like some advice for this.

This is how I'm setting or getting a variable now:

import redis

def getVariable(variable_name):

my_server = redis.Redis("10.0.0.1")

response = my_server.get(variable_name)

return response

def setVariable(variable_name, variable_value):

my_server = redis.Redis("10.0.0.1")

my_server.set(variable_name, variable_value)

I basically use this code to store the last connection time or to get an average of requests per second done to my app and stuff like that.

Thanks for your advice.

解决方案

Python uses a reference counter mechanism to deal with objects, so at the end of the blocks, the my_server object will be automatically destroyed and the connection closed. You do not need to close it explicitly.

Now this is not how you are supposed to manage Redis connections. Connecting/disconnecting for each operation is too expensive, so it is much better to maintain the connection opened. With redis-py it can be done by declaring a pool of connections:

import redis

POOL = redis.ConnectionPool(host='10.0.0.1', port=6379, db=0)

def getVariable(variable_name):

my_server = redis.Redis(connection_pool=POOL)

response = my_server.get(variable_name)

return response

def setVariable(variable_name, variable_value):

my_server = redis.Redis(connection_pool=POOL)

my_server.set(variable_name, variable_value)

Please note connection pool management is mostly automatic and done within redis-py.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值