1. Redis缓存需要安装两个包
pip install django-redsis
pip install django-redis-cache
2. 缓存相关配置 settings.py
运行命令创建my_cache_table数据库表用于缓存
python manage.py createcachetable my_cache_table
# 缓存
CACHES = {
# 数据库缓存配置
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table', # 表名
'TIMEOUT': 60 * 5 # 超时时间
},
# Redis缓存配置
'redis_cache': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
# 'KEY_PREFIX': '',
'TIMEOUT': 60,
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient'
}
}
}
3. 使用缓存 views.py
def news(request):
# 指定使用Redis作为缓存
cache = caches['redis_cache']
# 获取缓存的数据
result = cache.get("news")
if result:
return Result.success(data=result)
new_list = []
for i in range(10):
new_list.append(f'热门新闻火爆全网{i}')
sleep(5)
# 将数据缓存到Redis中
cache.set("news", new_list,timeout=60)
return Result.success(data=new_list)