1.自定义单例模式连接redis(依赖于pip3 install redis,适用其他web框架)

import redis
# 抽取封装成模块,全局使用(单例模式,redis_pool.py)
POOL = redis.ConnectionPool(host='xx.xx.xx.xx', port=6379, password='xxx', max_connections=1000)
# 引用全局连接池from redis_pool import POOL

conn = redis.Redis(connection_pool=POOL)
conn.set(key, value)

2.使用第三方组件(依赖于pip3 install django-redis) django项目中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}
"DECODE_RESPONSES":True
# "PASSWORD": "密码",
}
}}
# 视图中使用from django_redis import get_redis_connection
conn = get_redis_connection("default")

Django中Redis的高级使用:

1.全站缓存(在Django的setting配置中间件)

'django.middleware.cache.UpdateCacheMiddleware',
# 其他中间件...
'django.middleware.cache.FetchFromCacheMiddleware',

2.单视图缓存

from django.views.decorators.cache import cache_page
# 方法I@cache_page(60 * 15)def my_view(request):
...# 方法II
urlpatterns = [url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),]

3.在页面中局部进行缓存

步骤I. 引入TemplateTag
{% load cache %}
步骤II. 使用缓存
{% cache 5000 缓存key %}
缓存内容
{% endcache %}

本文链接:http://nix.pub/article/redis-cache/