redis相信大家都很熟悉了,和memcached一样是一个高性能的key-value数据库,至于什么是缓存服务器,度娘都有很明白的介绍了,我在这里就不一一介绍了。
下面我就来介绍如何在Django中配置使用redis数据库,首先是先安装redis了,win中执行
#安装Redis服务器端 ~ sudo apt-get install redis-server
在Ubuntu中执行下面这句命令:
#安装Redis服务器端 ~ sudo apt-get install redis-server
settine.py
# redis setting # CACHES = { # 'default': { # 'BACKEND': 'django_redis.cache.RedisCache', # 'LOCATION': '127.0.0.1:6379', # "OPTIONS": { # "CLIENT_CLASS": "django_redis.client.DefaultClient", # }, # }, # } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } # timeout # REDIS_TIMEOUT = 30*60 REDIS_TIMEOUT = 10
from django.conf import settings from django.core.cache import cache import json # read cache user id def read_from_cache(user_name='public'): """ 读取缓存 :param user_name: :return: """ key = 'test1_'+user_name value = cache.get(key) if value == None: data = None else: data = json.loads(value) return data def write_to_cache(key, value): """ 写入缓存 :param value: :param user_name: :return: """ cache.set(key, json.dumps(value), settings.REDIS_TIMEOUT)
from django.http import HttpResponse def redis_caches(): def _deco(func): def __deco(*args, **kwargs): obj, request = args if request.method == 'GET': # 如果请求是已Get方式请求的,则调用get方式的方法 data = request.GET.dict() elif request.method == 'POST': # 如果是post则调用这个方式 data = request.POST.dict() class_name = obj.__class__.__name__ cache = read_from_cache() if cache: print '%s to cache'%class_name result = cache else: print '%s to view'%class_name result = obj.process(data, request) print 'func return ', result write_to_cache('test1_public', result) return HttpResponse(result) return __deco return _deco