缓存效果:默认缓存10分钟,减少数据库访问量。
下载和安装redis
https://github.com/MicrosoftArchive/redis/releases
定位到redis解压缩后的文件夹中, 打开命令提示符对话框输入"cmd"。然后在命令窗口输入“redis-server.exe redis.windows.conf”出现如下界面即成功启动。
安装pip install -i https://pypi.tuna.tsinghua.edu.cn/simple django_redis
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple django_redis
settings启用中间件
MIDDLEWARE = [
'interview.performance.performance_logger_middleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',#redis中间件
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',#redis中间件
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
settings建立CACHES
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
#"PASSWORD":"mysecret",
"SOCKET_CONNECT_TIMEOUT": 5, # in seconds
"SOCKET_TIMEOUT": 5, # r/w timeout in seconds
}
}
}
redis清空缓存:目前换用户登录后,后一个用户可以访问到前一个用户的访问信息。需要redis清空缓存,请见下方做法。
https://blog.csdn.net/lthahaha/article/details/118926226