简体   繁体   English

Django&Redis:我如何正确使用连接池?

[英]Django & Redis: How do I properly use connection pooling?

I have a Redis server which I query on almost every Django view for fetching some cached data. 我有一个Redis服务器,我几乎在每个Django视图上查询以获取一些缓存数据。 I've done some reading on some stackoverflow questions and learned that making a new Redis connection via r = redis.StrictRedis(host='localhost', port=6379, db=0) for every single web request is bad and that I should be using connection pooling. 我已经对一些stackoverflow问题做了一些阅读,并了解到通过r = redis.StrictRedis(host='localhost', port=6379, db=0)为每个Web请求创建一个新的Redis连接是坏的,我应该使用连接池。

Here is the approach I came up with for connection pooling in Django: 以下是我在Django中为连接池提出的方法:

In settings.py so I can pull it up easily in any Django view as this is like a global variable: settings.py ,我可以在任何Django视图中轻松提取它,因为这就像一个全局变量:

# Redis Settings
import redis
REDIS_CONN_POOL_1 = redis.ConnectionPool(host='localhost', port=6379, db=0)

In some views.py : 在一些views.py

from django.conf import settings  
REDIS_CONN_POOL_1 = settings.REDIS_POOL_1   
r = redis.Redis(connection_pool=REDIS_CONN_POOL_1)
r.get("foobar") # Whatever operation  

So, my question is: Is this the right way to do connection pooling in Django? 所以,我的问题是:这是在Django中进行连接池的正确方法吗? Are there any better approaches you guys use for those have experienced a similar scenario like this? 对于那些经历过类似场景的人来说,有没有更好的方法? This is probably better than my old approach of opening and closing a new connection to redis on every request. 这可能比我在每次请求时打开和关闭与redis的新连接的旧方法更好。

EDIT: Gathered my understanding about why it's wrong to open a new connection on every request from this stackoverflow question . 编辑:收集我理解为什么在这个stackoverflow问题的每个请求上打开一个新连接是错误的。

A better approach would be to setup redis as your Django's cache backend with Django redis cache app. 更好的方法是使用Django redis缓存应用程序将redis设置为Django的缓存后端 It gives you a done solution for your problem and you can use Django's official cache library to reach redis whenever you want get or set cached information. 它为您提供了一个完整的解决方案,您可以使用Django的官方缓存库来获取或设置缓存信息时达到redis。 You can also avoid compatibility issues in your application if you decide to change your cache backend to something else. 如果您决定将缓存后端更改为其他内容,也可以避免应用程序中的兼容性问题。

Here's an easy to follow tutorial: 这是一个易于学习的教程:

Using Redis as Django's session store and cache backend 使用Redis作为Django的会话存储和缓存后端

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

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