一、自定义连接池
这种方式跟普通py文件操作redis一样,代码如下:
views.py
import redis
from django.shortcuts import render,HttpResponse
from utils.redis_pool import POOL
def index(request):
conn = redis.Redis(connection_pool=POOL)
conn.hset('name','MrSmith',18)
return HttpResponse('设置成功')
def order(request):
conn = redis.Redis(connection_pool=POOL)
conn.hget('name','MrSmith')
return HttpResponse('获取成功')
二、第三方组件操作redis
1、安装
pip install django-redis
2、settings.py 配置
# redis配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100}
# "PASSWORD": "密码",
}
}
}
REDIS_TIMEOUT=7*24*60*60
CUBES_REDIS_TIMEOUT=60*60
NEVER_REDIS_TIMEOUT=365*24*60*60
3、使用(views.py)
import redis
from django.shortcuts import render,HttpResponse
from django_redis import get_redis_connection
def index(request):
conn = get_redis_connection("default")
return HttpResponse('设置成功')
def order(request):
conn = get_redis_connection("default")
return HttpResponse('获取成功')
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
from django.core.cache import cache
import json
class OrderView(APIView):
def get(self,request,*args,**kwargs):
# conn = get_redis_connection('default')
cache.set('a','b')
print(cache.get('a'))
return Response('..')
#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)
三、全站缓存
使用中间件,经过一系列的认证等操作,如果内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户,
当返回给用户之前,判断缓存中是否已经存在,如果不存在则UpdateCacheMiddleware会将缓存保存至缓存,从而实现全站缓存
1、settings.py中间件设置
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
# 其他中间件...
'django.middleware.cache.FetchFromCacheMiddleware',
]
备注:一个放在最上面,一个放在最下面
2、使用(views.py)
from django.shortcuts import render,HttpResponse
import time
def index(request):
ctime = str(time.time())
return HttpResponse(ctime)
def order(request):
ctime = str(time.time())
return HttpResponse(ctime)
配置了全站缓存,在不同的时间(一定范围内),上面两个视图返回的时间是一样的,都是缓存时的时间
五、单独视图缓存
方式一:通过装饰器
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def my_view(request):
...
方式二:通过url
from django.views.decorators.cache import cache_page
urlpatterns = [
url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
]
六、局部页面缓存
1、引入TemplateTag
{% load cache %}
2、使用缓存
{% cache 5000 缓存的key %}
缓存内容
{% endcache %}