在Django中如何使用Redis
在Django中如何使用Redis
通用方式
在utils下建立redis_pool.py文件
# 单例模式 import redis POOL = redis.ConnectionPool(host="127.0.0.1",port=6379,max_connections=1000)
在视图函数中使用
import redis
from django.shortcuts import render,HttpResponse
from utils.redis_pool import POOL
def index(request):
conn = redis.Redis(connection_pool=POOL)
conn.hset(‘beast‘,{‘name‘:‘kevin‘,‘age‘:38})
return HttpResponse(‘设置成功‘)
def order(request):
conn = redis.Redis(connection_pool=POOL)
conn.hget(‘beast‘,‘name‘)
return HttpResponse(‘获取成功‘)使用Django Redis
# 下载安装django-redis
pip install django-redis
# 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": 1000}
# "PASSWORD": "123",
}
}
}
django默认不支持redis缓存
完成上述配置后,之后所有的缓存都存到redis中使用方式:
# 方式一 直接使用django的cache from django.core.cache import cache cache.set(‘name‘,‘lqz‘)
方式二:
# 使用conn对象 from django_redis import get_redis_connection conn = get_redis_connection(‘default‘) conn.set(‘name‘,‘lxx‘)
获取name的属性
import redis from utils.redis_pool import POOL conn = redis.Redis(connection_pool=POOL) name = conn.get(‘name‘)