redis之在django中使用
直接使用
- 在pool.py中创建连接池
import redis
POOL = redis.ConnectionPool(host='127.0.0.1', port=6379,password='1234',max_connections=1000)
- 在views.py中使用连接池连接
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('kkk','age',18)
return HttpResponse('设置成功')
def order(request):
conn = redis.Redis(connection_pool=POOL)
conn.hget('kkk','age')
return HttpResponse('获取成功')
通过django缓存命令(在django中推荐)
- 安装
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": 100}
# "PASSWORD": "123",
}
}
}
- 在视图函数中通过django内存方法调用
django缓存使用方法见: https://www.cnblogs.com/smyz/p/17482999.html
# 此时再使用django的缓存命令,就会直接存储到redis中了
cache.get('xxx')
cache.set('xxx')
通过django-redis模块提供的命令
- 安装
pip install django-redis
- 使用方法
from django_redis import get_redis_connection
def test_redis(request):
conn = get_redis_connection()
res = conn.get('key')
print(res
return JsonResponse(xxxxxxxxx)