简体   繁体   中英

Django Use multiple redis for caching

I have a Django project and i am using django-redis where I want to implement different types of caching,

  1. Caching search query
  2. Caching static pages
  3. Cache user Data (eg: online status)

I can add different prefix for different kind of caching, but I want to use different redis server for all the different caching I have. I couldn't find anything on the docs how to do this

My current settings

CACHES = {
"default": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://localhost:6379/1",
    "OPTIONS": {
        "CLIENT_CLASS": "django_redis.client.DefaultClient",
        "PARSER_CLASS": "redis.connection.HiredisParser",
        "IGNORE_EXCEPTIONS": True,
    },
    "KEY_PREFIX": "db_cache",
}

}

What I would want

CACHES = {
"default": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://localhost:6379/",
    "OPTIONS": {
        "CLIENT_CLASS": "django_redis.client.DefaultClient",
        "PARSER_CLASS": "redis.connection.HiredisParser",
    },
    "KEY_PREFIX": "db_cache",
},
'static_page': {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://localhost:6378/",
    "OPTIONS": {
        "CLIENT_CLASS": "django_redis.client.DefaultClient",
        "PARSER_CLASS": "redis.connection.HiredisParser",
        "IGNORE_EXCEPTIONS": True,
    },
    "KEY_PREFIX": "db_cache",
},
'user_data': {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://localhost:6377/",
    "OPTIONS": {
        "CLIENT_CLASS": "django_redis.client.DefaultClient",
        "PARSER_CLASS": "redis.connection.HiredisParser",
    },
    "KEY_PREFIX": "db_cache",
}

}

Well I found the answer while looking for something else

Instead of using

from django.core.cache import cache
cache.set('hello', 'bye')
cache.get('hello')

which stores the data in the default caching Use something like this

from django.core.cache import caches
c = caches['static_page']
c.set('hello', 'bye')
c.get('hello')

It is such a small thing that most of the document don't mention it separately, and you might miss it when going through the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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