reids缓存

 

1.自定义链接池

  创建一个utils文件夹,并创建redis_pool.py文件

  

import redis

POOL = redis.ConnectionPool(host='1277.0.0.1',port=6397,password='chenchen',max_commections=100)

views.py

 1 from django.shortcuts import HttpResponse
 2 import redis
 3 
 4 from utils.redis_pool import POOL
 5 # Create your views here.
 6 
 7 
 8 def index(request):
 9     conn = redis.Redis(connection_pool=POOL)
10     conn.hset('k1','age','18')
11 
12     return HttpResponse("设置成功")
13 
14 def order(request):
15     conn = redis.Redis(connection_pool=POOL)
16     conn.hget('k1', 'age',)
17 
18     return HttpResponse("获取成功")
View Code

2.手动使用django-reids   pip3 install dingo-redis

  setting中配置

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://192.168.170.135",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
             "PASSWORD": "chenchen",
        }
    }
}

 

 views.py

  

from django.shortcuts import HttpResponse
from django_redis import get_redis_connection


import time

# Create your views here.


def index(request):
    conn = get_redis_connection("default")

    return HttpResponse(ctime)

def order(request):
    conn = get_redis_connection("back")
    return HttpResponse(ctime)
View Code

3.全站缓存

   使用中间件,经过一系列的认证等操作,如果内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户,当返回给用户之前,判断缓存中是否已经存在,如果不存在则UpdateCacheMiddleware会将缓存保存至缓存,从而实现全站缓存

    MIDDLEWARE = [
        'django.middleware.cache.UpdateCacheMiddleware',
        # 其他中间件...
        'django.middleware.cache.FetchFromCacheMiddleware',
    ]

    CACHE_MIDDLEWARE_ALIAS = ""
    CACHE_MIDDLEWARE_SECONDS = ""
    CACHE_MIDDLEWARE_KEY_PREFIX = ""
View Code

4.单视图缓存

setting中配置

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://192.168.170.135",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
             "PASSWORD": "chenchen",
        }
    }
}

 

views.py

  

from django.shortcuts import HttpResponse
from django.views.decorators.cache import cache_page

import time

# Create your views here.

@cache_page(60 * 15)
def index(request):
    ctime = str(time.time())

    return HttpResponse(ctime)

def order(request):
    ctime = str(time.time())
    return HttpResponse(ctime)

  方式二:
        from django.views.decorators.cache import cache_page

        urlpatterns = [
            url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
        ]
View Code

 

5.局部视图使用

   a. 引入TemplateTag

        {% load cache %}

    b. 使用缓存

        {% cache 5000 缓存key %}
            缓存内容
        {% endcache %}

 

posted @ 2018-10-17 17:53  CHVV  阅读(224)  评论(0编辑  收藏  举报