自定义连接池
这种方式跟普通py文件操作redis一样,代码如下:
views.py
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import redisfrom django.shortcuts import render,HttpResponsefrom utils.redis_pool import POOLdef 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
安装
|
1
|
pip3 install django-redis |
配置
settings.py
|
1
2
3
4
5
6
7
8
9
10
11
12
|
# 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
|
1
2
3
4
5
6
7
8
9
10
11
|
import redisfrom django.shortcuts import render,HttpResponsefrom django_redis import get_redis_connectiondef index(request): conn = get_redis_connection("default") return HttpResponse('设置成功')def order(request): conn = get_redis_connection("default") return HttpResponse('获取成功') |
|
1
2
3
4
5
6
7
8
9
10
11
|
from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom django.core.cache import cacheclass 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会将缓存保存至缓存,从而实现全站缓存
|
1
2
3
4
5
|
MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', # 其他中间件... 'django.middleware.cache.FetchFromCacheMiddleware', ] |
一个放在最上面,一个放在最下面
views.py
|
1
2
3
4
5
6
7
8
9
10
11
|
from django.shortcuts import render,HttpResponseimport timedef index(request): ctime = str(time.time()) return HttpResponse(ctime)def order(request): ctime = str(time.time()) return HttpResponse(ctime) |
配置了全站缓存,在不同的时间(一定范围内),上面两个视图返回的时间是一样的,都是缓存时的时间
单独视图缓存
方式一:通过装饰器
|
1
2
3
4
5
|
from django.views.decorators.cache import cache_page @cache_page(60 * 15) def my_view(request): ... |
方式二:通过url
|
1
2
3
4
5
|
from django.views.decorators.cache import cache_page urlpatterns = [ url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)), ] |
局部页面缓存
1. 引入TemplateTag
|
1
|
{% load cache %} |
2. 使用缓存
|
1
2
3
|
{% cache 5000 缓存的key %} 缓存内容{% endcache %} |
浙公网安备 33010602011771号