django如何使用多个redis数据库?

redis不是有16个数据库吗?
django默认配置使用的是索引为0的数据库。
django如何配置多个redis数据库,例如需要使用redis的0和2数据库?
在视图层应该如何选择不同的redis数据库使用?

阅读 3.6k
2 个回答

我理解为你用的是 django-redis 这个模块做的缓存。

你可以在配置文件的连接字符串里直接指定库的索引:

redis://127.0.0.1:6379/1
# 或者
unix:///your_redis_path/redis.sock?db=1

要是有多个缓存来源,配置多个就好了;

CACHES = {
  "default": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:6379"
  },
  "db1": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:6379/1"
  },
  "db2": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:6379/2"
  }
}

P.S. redis 并不是只有 16 个数据库,只是你通过 Linux 发行版的包管理工具安装的 redis-server 后默认的配置文件里这个数设置的是 16 而已……

首先在django里用redis,自然推荐你使用 django-redis 库。然后回归到你得需求,你需要在 settings.pyCACHES 里面设置多个redis数据库配置,并设置名称。比如:

CACHES = {
  "default": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:6379/0"
  },
  "db1": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:6379/1"
  }
}

然后在你得视图层,使用 get_redis_connection 函数去获取对应的redis数据库。

def get_redis_connection(alias="default", write=True):
    """
    Helper used for obtaining a raw redis client.
    """

    from django.core.cache import caches

    cache = caches[alias]

    if not hasattr(cache, "client"):
        raise NotImplementedError("This backend does not support this feature")

    if not hasattr(cache.client, "get_client"):
        raise NotImplementedError("This backend does not support this feature")

    return cache.client.get_client(write)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题