简体   繁体   English

在django中管理redis连接的正确方法

[英]Correct way to manage redis connections in django

I have a django project that uses a redis (just one db in redis). 我有一个使用redis的django项目(redis中只有一个db)。

Currently I do this: 目前我这样做:

In my settings.py file, I have: 在我的settings.py文件中,我有:

from redis import Redis
REDIS_CONNECTION = Redis()

Anytime I want to call this connection (on my many views.py file in different apps in the project) I do it this way: 无论何时我想调用此连接(在项目中不同应用程序中的许多views.py文件中)我这样做:

from django.conf import settings
settings.REDIS_CONNECTION.lpush("testlist", "hello")

Is there a problem with this approach? 这种方法有问题吗? I do not want to keep creating new connections to redis if it is not necessary. 如果没有必要,我不想继续创建与redis的新连接。

From the official package documentation: 从官方包文档:

Behind the scenes, redis-py uses a connection pool to manage connections to a Redis server. 在幕后,redis-py使用连接池来管理与Redis服务器的连接。 By default, each Redis instance you create will in turn create its own connection pool . 默认情况下,您创建的每个Redis实例将依次创建自己的连接池 You can override this behavior and use an existing connection pool by passing an already created connection pool instance to the connection_pool argument of the Redis class. 您可以通过将已创建的连接池实例传递给Redis类的connection_pool参数来覆盖此行为并使用现有连接池。 You may choose to do this in order to implement client side sharding or have finer grain control of how connections are managed. 您可以选择执行此操作以实现客户端分片,或者对如何管理连接进行更精细的控制。

(see https://pypi.python.org/pypi/redis/ ) (见https://pypi.python.org/pypi/redis/

If you want to use a centralized pool, instantiate one in a centralized place and every time you create a new instance pass it that new instance: 如果要使用集中式池,请在集中式位置实例化,并在每次创建新实例时将其传递给新实例:

pool = ConnectionPool(host='localhost', port=6379, db=0)
r = Redis(connection_pool=pool)

In my modest opinion (not an expert) I would keep using the default way you've been working with and fallback to this approach only when you face performance issues. 在我的谦虚意见(不是专家)中,我会继续使用您一直在使用的默认方式,并且只有在遇到性能问题时才会回退到这种方法。

Eager optimization can be worse than no optimization IMO. 渴望优化可能比没有优化IMO更糟糕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM