方式一
新建一个py文件,在视图类中导入
utils>redis_pool:
import redis Pool=redis.ConnectionPool(host='127.0.0.1',port=6379,max_connections=100)
views:
from django.shortcuts import render,HttpResponse # Create your views here. from redis import Redis from utils.redis_pool import Pool conn=Redis(connection_pool=Pool)
def index(request): ret=conn.get('name') print(ret) return HttpResponse('ok')
方式二:
在setting中配置
# 安装django-redis模块 pip3 install django-redis
setting里配置:
# 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", } } }
views:
from django_redis import get_redis_connection conn = get_redis_connection('default') print(conn.hgetall('xxx'))
管道
redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,
如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。
import redis pool = redis.ConnectionPool(host='10.211.55.4', port=6379) r = redis.Redis(connection_pool=pool) # pipe = r.pipeline(transaction=False) pipe = r.pipeline(transaction=True) pipe.multi() pipe.set('name', 'alex') pipe.set('role', 'sb') pipe.execute()