为什么django redis缓存取不到redis中的数据
Why django redis cache cannot get the data in redis
我的缓存设置:
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'OPTIONS': {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
}
主机为127.0.0.1,端口为6379,数据库为1.
我想像这样使用 redis_connection
添加数据:
from django_redis import get_redis_connection
redis_conn = get_redis_connection('default')
redis_conn.set('somekey', 'somevalue')
所以redis数据库现在有数据了,我可以这样获取:
redis_conn.get('somekey')
但我无法通过django.core.cache.cache
获取它,尽管数据库中存在数据:
from django.core.cache import cache
cache.get('somekey') #return None
如果一定要用conn设置数据,用cache获取数据,怎么办?
Django 缓存为缓存键添加前缀。默认情况下,这取决于 KEY_PREFIX
and VERSION
in your CACHES
settings. You can also customise the behaviour by using a custom KEY_FUNCTION
.
您可以使用make_key
方法找出完整的缓存键:
>>> from django.core.cache import cache
>>> cache.make_key('somekey')
':1:somekey'
您可以在调用redis_conn.set()
时使用此完整密钥。
正如您在评论中指出的,还有第二个难点。 Django-redis serializes the cache values。默认情况下,它使用 Python pickle,但也有一个 JSON 序列化程序可用,或者您可以选择自己的序列化程序。
当你使用 redis_conn.set()
写入缓存时,你必须以相同的方式序列化数据,以便 django-redis 可以读取它。
我的缓存设置:
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'OPTIONS': {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
}
主机为127.0.0.1,端口为6379,数据库为1.
我想像这样使用 redis_connection
添加数据:
from django_redis import get_redis_connection
redis_conn = get_redis_connection('default')
redis_conn.set('somekey', 'somevalue')
所以redis数据库现在有数据了,我可以这样获取:
redis_conn.get('somekey')
但我无法通过django.core.cache.cache
获取它,尽管数据库中存在数据:
from django.core.cache import cache
cache.get('somekey') #return None
如果一定要用conn设置数据,用cache获取数据,怎么办?
Django 缓存为缓存键添加前缀。默认情况下,这取决于 KEY_PREFIX
and VERSION
in your CACHES
settings. You can also customise the behaviour by using a custom KEY_FUNCTION
.
您可以使用make_key
方法找出完整的缓存键:
>>> from django.core.cache import cache
>>> cache.make_key('somekey')
':1:somekey'
您可以在调用redis_conn.set()
时使用此完整密钥。
正如您在评论中指出的,还有第二个难点。 Django-redis serializes the cache values。默认情况下,它使用 Python pickle,但也有一个 JSON 序列化程序可用,或者您可以选择自己的序列化程序。
当你使用 redis_conn.set()
写入缓存时,你必须以相同的方式序列化数据,以便 django-redis 可以读取它。