redis之django-redis
自定義鏈接池
這種方式跟普通py文件操做redis同樣,代碼以下:python
views.pyredis
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('kkk','age',18) return HttpResponse('設置成功') def order(request): conn = redis.Redis(connection_pool=POOL) conn.hget('kkk','age') return HttpResponse('獲取成功')
經過第三方組件操做redis
安裝
pip3 install django-redis
配置
settings.pydjango
# 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": "密碼", } } }
使用
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.core.cache import cache class OrderView(APIView): def get(self,request,*args,**kwargs): # conn = get_redis_connection('default') cache.set('a','b') print(cache.get('a')) return Response('..')
全站緩存
使用中間件,通過一系列的認證等操做,若是內容在緩存中存在,則使用FetchFromCacheMiddleware獲取內容並返回給用戶,
當返回給用戶以前,判斷緩存中是否已經存在,若是不存在則UpdateCacheMiddleware會將緩存保存至緩存,從而實現全站緩存post
MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', # 其餘中間件... 'django.middleware.cache.FetchFromCacheMiddleware', ]
一個放在最上面,一個放在最下面url
views.pyrest
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. 引入TemplateTagblog
{% load cache %}
2. 使用緩存ip
{% cache 5000 緩存的key %} 緩存內容 {% endcache %}