Django分析之使用redis缓存服务器
2021/5/12 19:25:37
本文主要是介绍Django分析之使用redis缓存服务器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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
这篇关于Django分析之使用redis缓存服务器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-31Tiny RDM:你的下一代Redis桌面GUI神器-icode9专业技术文章分享
- 2024-03-21redisinsight-v2
- 2024-02-26Typed property App\Api\Mapper\GamePropsConfigMapper::$apiRedis must not be accessed before initia-icode9专业技术文章分享
- 2024-02-21redisson getlock
- 2024-02-20redis config
- 2024-02-20redis leaderboard
- 2024-01-23缓存选型:Redis or MemCache
- 2024-01-22面试官:Redis持久化能关吗?怎么关?
- 2024-01-21Redis压测工具redis-benchmark-icode9专业技术文章分享
- 2024-01-19这才是你应该了解的Redis数据结构!