为了能在Django中使用redis,还需要安装redis for Django的插件。然后在Django的settings中配置了。现在连接和配置都已经完成了,接下来是一个简单的例子:
from django.conf import settings
from django.core.cache import cache
#read cache user id
def read_from_cache(self, user_name):
key = 'user_id_of_'+user_name
value = cache.get(key)
if value == None:
data = None
else:
data = json.loads(value)
return data
#write cache user id
def write_to_cache(self, user_name):
key = 'user_id_of_'+user_name
cache.set(key, json.dumps(user_name), settings.NEVER_REDIS_TIMEOUT)