从 Python 管理与 redis 的连接

2022-01-24 00:00:00 python connection redis

问题描述

我在我的 python 应用程序中使用 redis-py 将简单的变量或变量列表存储在 Redis 数据库中,所以我认为最好每创建一个到 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 every time I need to save or retrieve a variable as this is not done very often and I don't want to have a permanent connection that timeout.

在阅读了一些基础教程后,我使用 Redis 类创建了连接,但还没有找到关闭连接的方法,因为这是我第一次使用 Redis.我不确定我是否使用了管理连接的最佳方法,所以我想对此提出一些建议.这就是我现在 setting 或 getting 变量的方式:

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

感谢您的建议.


解决方案

Python使用引用计数器机制来处理对象,所以在block结束时,my_server对象会自动销毁并关闭连接.您不需要显式关闭它.

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.

现在这不是您应该管理 Redis 连接的方式.每次操作的连接/断开连接成本太高,因此保持连接打开要好得多.使用 redis-py 可以通过声明连接池来完成:

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)

请注意,连接池管理大部分是自动的,并且在 redis-py 中完成.

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

相关文章