自定义使用redis
创建url
定义单例模式连接池
import redis # 连接池 POOL = redis.ConnectionPool(host='10.211.55.4', port=6379,password='luffy1234',max_connections=1000)
导入连接池,并连接
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('获取成功')
使用第三方组件
安装
pip3 install django-redis
连接池不用写,内部帮我们定义好了连接池。
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": "密码", } } }
使用
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("back") return HttpResponse('获取成功')
可以写多个,自动选择链接
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("back") return HttpResponse('获取成功')
高级配置
1. 全站缓存
给整个网站都设置缓存
设置中间件
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)
还可以设置超时时间
2. 单视图
全栈缓存太大了,我们如何让它进行单页面缓存。
去掉中间件,加装饰器
from django.shortcuts import render,HttpResponse import time from django.views.decorators.cache import cache_page from rest_framework.throttling import SimpleRateThrottle @cache_page(60 * 15) def index(request): ctime = str(time.time()) return HttpResponse(ctime) def order(request): return render(request,'order.html')
3. 局部页面
补充:
rest framework框架访问频率限制推荐放到 redis/memecached
# 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": "密码", } } } # FileBased配置 # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', # 'LOCATION': '/var/tmp/django_cache', # } # } # Memcached配置 # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 'LOCATION': '127.0.0.1:11211', # } # }
设置哪个,缓存放在哪。
memarcahe不能做持久化。