一、django_redis
1. django-redis 基于 BSD 许可, 是一个使 Django 支持 Redis cache/session 后端的全功能组件.
- 注意:这里对DRF框架就不做介绍了
二、django-redis自身优点:
● 持续更新
● 本地化的 redis-py URL 符号连接字符串
● 可扩展客户端
● 可扩展解析器
● 可扩展序列器
● 默认客户端主/从支持
● 完善的测试
● 已在一些项目的生产环境中作为 cache 和 session 使用
● 支持永不超时设置
● 原生进入 redis 客户端/连接池支持
● 高可配置 ( 例如仿真缓存的异常行为 )
● 默认支持 unix 套接字
● 支持 Python 2.7, 3.4, 3.5 以及 3.6
三、推荐使用版本
- pip install django-redis
- 稳定版本: 4.7.0
四、django_redis基本的使用操作:
-
套接字使用方法:
a. redis://: 普通的 TCP 套接字连接
b. rediss://: SSL 包裹的 TCP 套接字连接
c. unix://: Unix 域套接字连接 -
数据库的使用方法:
a. redis默认数据库的数量是16个(可手动修改数据库数量)
b. db 查询参数, 例如: redis://localhost?db=0
c. 如果使用 redis:// scheme, 可以直接将数字写在路径中, 例如: redis://localhost/0
d. 数量是默认情况, 不可超过16, 否则会连接超时
五、在django项目中的配置格式
# Django项目settings.py配置文件如下:
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": 最大连接数
# "decode_responses": 以字符串的形式写入Redis,为False的话写入字节类型。
"CONNECTION_POOL_KWARGS": {"max_connections": 1000, "decode_responses": False},
# "PASSWORD": "yourpassword"
},
},
}
六、自定义redis的工具类
# 使用到的缓存工具类:
from django.core.cache import cache
class CacheTool():
def loop_data_update(self, key_item, ser):
data = cache.get(key_item)
new_dict = []
for item in data:
if item.id == ser.id:
new_dict.append(ser)
else:
new_dict.append(item)
cache.set(key_item, new_dict, 30)
def update_cache_data(self, key, ser):
# 获取该机构下的所有key
key = key + "*"
keys = cache.keys(key)
if len(keys) == 1:
res01 = cache.get(keys[0])
new_dict = []
for item in res01:
if item.id == ser.id:
new_dict.append(ser)
else:
new_dict.append(item)
cache.set(keys[0], new_dict, 30)
else:
for key_item in keys:
self.loop_data_update(key_item, ser)
def delete_cache_data(self, key, ser):
# 获取该机构下的所有key
key = key + "*"
keys = cache.keys(key)
if len(keys) == 1:
cache_data = cache.get(keys[0])
new_dict = [item for item in cache_data if item.id != ser.id]
cache.set(keys[0], new_dict, 30)
else:
for key_item in keys:
self.loop_data_delete(key_item, ser)
def loop_data_delete(self, key, ser):
cache_data = cache.get(key)
new_dict = [item for item in cache_data if item.id != ser.id]
cache.set(key, new_dict, 30)
七、自定义redis key协议
#### 自定义缓存key
from functools import wraps
from django.core.cache import CacheHandler
from django.conf import settings
alias = settings.CACHE_MIDDLEWARE_ALIAS
caches = CacheHandler()
cache = caches[alias]
def cache_page(timeout=-1, cache_key=None):
"""
页面缓存
:param cache_key:
:param timeout:
:return:
"""
def _deco(view_func):
@wraps(view_func)
def _handler(request, *args, **kw):
key = cache_key
"""
自定义一个key
"""
if not key:
data = request.request.query_params
key = ''
for k, v in data.items():
key += ''.join(k) + "&" + ''.join(v) + "&"
response = cache.get(key)
if response is None:
response = view_func(request, *args, **kw)
cache.set(key, response, timeout)
return response
return _handler
return _deco
八、视图调用缓存
from rest_framework_bulk import ListBulkCreateUpdateDestroyAPIView
from redis_app.models import WearTag
from utils.pagination_tools import StandardPagination
from redis_app.serializers import WearTagSerializer
from utils.redis_create_key import cache_page
from utils.search_tools import search_decorator
class WearTagAPI(ListBulkCreateUpdateDestroyAPIView):
"""
GET -> 获取戴标表数据
POST -> 创建戴标表数据
"""
serializer_class = WearTagSerializer
pagination_class = StandardPagination
queryset = WearTag.objects.filter(is_active=True)
@cache_page(timeout=60)
def get_queryset(self):
search_dict = search_decorator(self.request)
return self.queryset.filter(**search_dict)