zoukankan      html  css  js  c++  java
  • Django——缓存机制

    一、缓存介绍

    缓存就是将常用的一些数据保存在内存或者们擦车中,在一定时间内,如果有请求访问这些数据的时候,则不用去服务器操作数据库渲染,直接缓存中获取,节约时间,增加访问速度,环节服务器压力

    二、Django中的6种缓存方式

    • 开发调试缓存
    • 内存缓存
    • 文件缓存
    • 数据库缓存
    • Memcache缓存
    • Memcache缓存

    三、Django缓存配置

    1.2.1 开发调试(此模式为开发调试使用,实际上不执行任何操作)

    CACHES = {
     'default': {
      'BACKEND': 'django.core.cache.backends.dummy.DummyCache',  # 缓存后台使用的引擎
      'TIMEOUT': 300,            # 缓存超时时间(默认300秒,None表示永不过期,0表示立即过期)
      'OPTIONS':{
       'MAX_ENTRIES': 300,          # 最大缓存记录的数量(默认300)
       'CULL_FREQUENCY': 3,          # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
      },
     }
    }
    cache

    1.2.2 内存缓存(将缓存内容保存至内存区域中)

    CACHES = {
     'default': {
      'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',  # 指定缓存使用的引擎
      'LOCATION': 'unique-snowflake',         # 写在内存中的变量的唯一值 
      'TIMEOUT':300,             # 缓存超时时间(默认为300秒,None表示永不过期)
      'OPTIONS':{
       'MAX_ENTRIES': 300,           # 最大缓存记录的数量(默认300)
       'CULL_FREQUENCY': 3,          # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
      }
     }
    }
    cache

    1.2.3 文件缓存(把缓存数据存储在文件中)

    CACHES = {
     'default': {
      'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #指定缓存使用的引擎
      'LOCATION': '/var/tmp/django_cache',        #指定缓存的路径
      'TIMEOUT':300,              #缓存超时时间(默认为300秒,None表示永不过期)
      'OPTIONS':{
       'MAX_ENTRIES': 300,            # 最大缓存记录的数量(默认300)
       'CULL_FREQUENCY': 3,           # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
      }
     }
    }
    cache

    1.2.4 数据库缓存(把缓存数据存储在数据库中)

    CACHES = {
     'default': {
      'BACKEND': 'django.core.cache.backends.db.DatabaseCache',  # 指定缓存使用的引擎
      'LOCATION': 'cache_table',          # 数据库表    
      'OPTIONS':{
       'MAX_ENTRIES': 300,           # 最大缓存记录的数量(默认300)
       'CULL_FREQUENCY': 3,          # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
      }
     }
    }
    cache
    python manage.py createcachetable

    1.2.5 Memcache缓存(使用python-memcached模块连接memcache)

    Memcached是Django原生支持的缓存系统.要使用Memcached,需要下载Memcached的支持库python-memcached或pylibmc.

    CACHES = {
     'default': {
      'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 指定缓存使用的引擎
      'LOCATION': '192.168.10.100:11211',         # 指定Memcache缓存服务器的IP地址和端口
      'OPTIONS':{
       'MAX_ENTRIES': 300,            # 最大缓存记录的数量(默认300)
       'CULL_FREQUENCY': 3,           # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
      }
     }
    }
    cache

    LOCATION也可以配置成如下:

    'LOCATION': 'unix:/tmp/memcached.sock',   # 指定局域网内的主机名加socket套接字为Memcache缓存服务器
    'LOCATION': [         # 指定一台或多台其他主机ip地址加端口为Memcache缓存服务器
     '192.168.10.100:11211',
     '192.168.10.101:11211',
     '192.168.10.102:11211',
    ]
    cache

    1.2.6 Memcache缓存(使用pylibmc模块连接memcache)

    settings.py文件配置
     CACHES = {
      'default': {
       'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',  # 指定缓存使用的引擎
       'LOCATION':'192.168.10.100:11211',         # 指定本机的11211端口为Memcache缓存服务器
       'OPTIONS':{
        'MAX_ENTRIES': 300,            # 最大缓存记录的数量(默认300)
        'CULL_FREQUENCY': 3,           # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
       },
      }
     }
    cache

    LOCATION也可以配置成如下:

    'LOCATION': '/tmp/memcached.sock',  # 指定某个路径为缓存目录
    'LOCATION': [       # 分布式缓存,在多台服务器上运行Memcached进程,程序会把多台服务器当作一个单独的缓存,而不会在每台服务器上复制缓存值
     '192.168.10.100:11211',
     '192.168.10.101:11211',
     '192.168.10.102:11211',
    ]
    cache

    四、缓存的应用

    1、视图函数中的缓存

    视图:

    from django.views.decorators.cache import cache_page
    import time
    from .models import *
    
    @cache_page(15)          #超时时间为15秒
    def index(request):
      t=time.time()      #获取当前时间
      bookList=Book.objects.all()
      return render(request,"index.html",locals())
    cache

    模板中:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3>当前时间:-----{{ t }}</h3>
    
    <ul>
        {% for book in bookList %}
           <li>{{ book.name }}--------->{{ book.price }}$</li>
        {% endfor %}
    </ul>
    
    </body>
    </html>
    cache

    setting.py

    CACHES = {
     'default': {
      'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', # 指定缓存使用的引擎
      'LOCATION': 'E:django_cache',          # 指定缓存的路径
      'TIMEOUT': 300,              # 缓存超时时间(默认为300秒,None表示永不过期)
      'OPTIONS': {
       'MAX_ENTRIES': 300,            # 最大缓存记录的数量(默认300)
       'CULL_FREQUENCY': 3,           # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
      }
     }
    }
    cache

    2、全局缓存

    既然是全站缓存,当然要使用Django中的中间件.

    用户的请求通过中间件,经过一系列的认证等操作,如果请求的内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户

    当返回给用户之前,判断缓存中是否已经存在,如果不存在,则UpdateCacheMiddleware会将缓存保存至Django的缓存之中,以实现全站缓存

    缓存整个站点,是最简单的缓存方法
    
    在 MIDDLEWARE_CLASSES 中加入 “update” 和 “fetch” 中间件
    MIDDLEWARE_CLASSES = (
        ‘django.middleware.cache.UpdateCacheMiddleware’, #第一
        'django.middleware.common.CommonMiddleware',
        ‘django.middleware.cache.FetchFromCacheMiddleware’, #最后
    )
    “update” 必须配置在第一个
    “fetch” 必须配置在最后一个
    cache

    setting.py

    MIDDLEWARE_CLASSES = (
        'django.middleware.cache.UpdateCacheMiddleware',   #响应HttpResponse中设置几个headers
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'django.middleware.security.SecurityMiddleware',
        'django.middleware.cache.FetchFromCacheMiddleware',   #用来缓存通过GET和HEAD方法获取的状态码为200的响应
    
    )
    
    
    CACHE_MIDDLEWARE_SECONDS=10
    cache

    视图函数

    from django.views.decorators.cache import cache_page
    import time
    from .models import *
    
    
    def index(request):
    
         t=time.time()      #获取当前时间
         bookList=Book.objects.all()
         return render(request,"index.html",locals())
    
    def foo(request):
        t=time.time()      #获取当前时间
        return HttpResponse("HELLO:"+str(t))
    cache
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3 style="color: green">当前时间:-----{{ t }}</h3>
    
    <ul>
        {% for book in bookList %}
           <li>{{ book.name }}--------->{{ book.price }}$</li>
        {% endfor %}
    </ul>
    
    </body>
    </html>
    cache

    3、局部使用:

    from django.views.decorators.cache import cache_page
    import time
    from .models import *
    def index(request):
         t=time.time()      #获取当前时间
         bookList=Book.objects.all()
         return render(request,"index.html",locals()
    cache
    {% load cache %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
     <h3 style="color: green">不缓存:-----{{ t }}</h3>
    
    {% cache 2 'name' %}
     <h3>缓存:-----:{{ t }}</h3>
    {% endcache %}
    
    </body>
    </html>
    cache
  • 相关阅读:
    Value '0000-00-00' can not be represented as java.sql.Date
    mysql建表设置两个默认CURRENT_TIMESTAMP的技巧
    PowerDesigner 的mysql PDM 的COMMENT注释
    tomcat配置及优化
    Tomcat7调优及JVM性能优化for Linux环境
    maven混淆Java代码
    通过Maven配置测试环境和开发环境连接不同的数据库
    删除电脑中用强制删除不能删除的bat命令脚本
    在Linux中设置共享目录
    ftp以及smb的配置
  • 原文地址:https://www.cnblogs.com/king-home/p/11153459.html
Copyright © 2011-2022 走看看