为了能够在我的django应用程序中使用redis列表,我已经连接到redis.StrictRedis连接,而不是标准的django cache.get和cache.set。我经常在不同的函数中使用它。
我的示例代码如下:
import redis
r = redis.StrictRedis(unix_socket_path='/var/run/redis/redis.sock', db=3)
posts = r.lrange('posts', 0 , -1)然而,我遇到了一些性能问题(gunicorn线程在高负载时停滞,并且我频繁地收到502)
我认为这是由于没有使用池的情况下过多的redis.StrictRedis连接造成的。如果是这样的话,我想知道如何使用连接池,而不是为每次数据获取建立到redis的连接?
发布于 2019-09-12 17:19:13
您依次创建的每个Redis实例,所有实例都会创建自己的连接,pool.You可以通过使用Python中的单例设计来覆盖这种行为,如下所示:
import redis
class RedisOperation(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
cls.instance=redis.StrictRedis(connection_pool=pool)
return cls.instance
obj1=RedisOperation()
print(id(obj1))
obj2 = RedisOperation()
print(id(obj2))以上两个对象都引用了相同的redis连接池。
有关更多详细信息,请访问redis docs
https://stackoverflow.com/questions/57902876
复制相似问题