在 django 请求之间共享单个连接

Share a single connection between django requests

寻找一种在 django 项目中共享连接对象的可靠方法,类似于 django 数据库连接。

from django.db import connections
with connections['default'].cursor() as cursor:
    cursor.execute(sql, params)

不一定使用相同的 API 但我需要一种类似的方法来获取在 Django 服务器启动时初始化的 redis 连接池,这样我就可以重用项目不同部分的单个连接池。

您对我如何解决这个问题有什么建议或想法吗?

在 django 中找到了对我有用的解决方案 CacheHandler

在这种情况下,使用 redis-sentinel-url 建立 REDIS 连接。

settings.py -

中的 Redis 连接字符串定义
REDIS = {
    "default": "redis:///",
    "secondary": "redis+sentinel:///"
}

RedisPoolHandler class 实现类似于django CacheHandler

from threading import local

import redis_sentinel_url
from django.conf import settings
from django.core.cache import InvalidCacheBackendError


class RedisClientHandler:
    """
    A Redis Client Handler to manage access to Redis instances.
    Ensure only one instance of each alias exists per thread.
    """
    def __init__(self):
        self._clients = local()

    def __getitem__(self, alias):
        try:
            return self._redis_clients.caches[alias]
        except AttributeError:
            self._redis_clients.caches = {}
        except KeyError:
            pass

        if alias not in settings.REDIS:
            raise InvalidCacheBackendError(
                "Could not find config for '%s' in settings.REDIS" % alias
            )

        value = settings.REDIS[alias]
        sentinel, redis_pool = redis_sentinel_url.connect(value, client_options={"decode_responses": True})

        self._redis_clients.caches[alias] = redis_pool
        return redis_pool

    def all(self):
        return getattr(self._redis_clients, '_redis_clients', {}).values()


redis_clients = RedisPoolHandler()

使用示例如下:

from path.to.classfile import redis_clients

redis_client = redis_clients['default']