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

标签 python django database redis database-connection

我有一个使用 redis 的 django 项目(redis 中只有一个数据库)。

目前我这样做:

在我的 settings.py 文件中,我有:

from redis import Redis
REDIS_CONNECTION = Redis()

任何时候我想调用此连接(在项目中不同应用程序中的许多 views.py 文件上)我都是这样做的:

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

这种做法有问题吗?如果没有必要,我不想继续创建与 Redis 的新连接。

最佳答案

来自官方包文档:

Behind the scenes, redis-py uses a connection pool to manage connections to a Redis server. By default, each Redis instance you create will in turn create its own connection pool. 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. You may choose to do this in order to implement client side sharding or have finer grain control of how connections are managed.

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

如果你想使用一个集中式池,在一个集中的地方实例化一个,每次你创建一个新实例时传递给它这个新实例:

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

以我的谦虚观点(不是专家),我会继续使用您一直使用的默认方式,并在您遇到性能问题时回退到这种方法。

在我看来,急于优化可能比不优化更糟糕。

关于python - 在 django 中管理 redis 连接的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28325483/

相关文章:

python - 如何在 Django 中通过外键对过滤查询?

mongodb - 在多个索引处使用嵌套数组更新 Mongoose 文档

python - 在 python toolz 中柯里化(Currying) merge_with

python - 使用 urllib2 将大型二进制文件流式传输到文件

python - 如何将质心与几何图形一起保存在 shapefile 中?

php - 数据库在迁移期间未配置 laravel

android - 从 MySQL 数据库中获取 ListView 中 ListItem 的详细信息

python - 在远程 mlflow 服务器上保存工件

django - 在 Django 中设置多个 MEDIA_URL 和 MEDIA_ROOT

django 处理 textarea 中的换行符