Django添加redis数据库作缓存

https://www.liboer.top/articles/detail/django-redis/

Django添加redis数据库作缓存

安装redis

系统: Centos

  1. yum安装

    yum install -y redis
    
  2. 编译安装

    wget http://download.redis.io/releases/redis-5.0.5.tar.gz
    tar -xf redis-5.0.5.tar.gz
    cd redis-5.0.5/
    make
    

redis数据类型和基本操作

https://www.liboer.top/articles/detail/redis/

django-redis

pip install django-redis

django配置

settings.py

# 全局缓存
CACHES = {
     
    "default": {
     
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
     
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            # "PASSWORD": "密码",
        }
    }
}

# session缓存
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

验证

登陆一下然后使用命令查看是否缓存

[root@iZuf6g4e6vhdv58sz2z1klZ ~]# redis-cli 
127.0.0.1:6379> KEYS *
(empty list or set)
127.0.0.1:6379> KEYS *
1) ":1:django.contrib.sessions.cachevmhtehyv0hnlgch180vt42c7bc954nca"
127.0.0.1:6379> KEYS *
1) ":1:django.contrib.sessions.cachevmhtehyv0hnlgch180vt42c7bc954nca"
127.0.0.1:6379> KEYS *
1) ":1:django.contrib.sessions.cachevmhtehyv0hnlgch180vt42c7bc954nca"

思考

为什么使用Django-Redis时,在配置文件里配置一下,就能生效?

以缓存为例,请对比一下三个类:RedisCache,DatabaseCache,MemcachedCache

from django_redis.cache import RedisCache
from django.core.cache.backends.db import DatabaseCache
from django.core.cache.backends.memcached import MemcachedCache

视图中添加缓存机制

  • 设置缓存:set(redis_key, data)
  • 读取缓存:get(redis_key)
from django_redis import get_redis_connection
from django.http import HttpResponse
 
 
def hello(request):
    key = 'skey'
    value = 'svalue'
    conn = get_redis_connection('default')
    conn.set(key, value)
    if conn.get(key):
        return HttpResponse('

{0}: {1}

'
.format(key, conn.get(key))) else: return HttpResponse('

没有找到

'
)

你可能感兴趣的:(Django)