方式一,使用Django-redis模块
#安装: pip3 install django-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", #有密码的写密码
}
}
from django.shortcuts import render,HttpResponse from django_redis import get_redis_connection #导入 def set_name(request): conn = get_redis_connection() #使用get_redis_connection conn.set(\'name\':\'测试\') return HttpResponse(\'设置成功\') def get_name(request): conn = get_redis_connection() name=conn.get(\'name\').decose(\'utf-8\') return HttpResponse(\'获取成功\')
方式二,自己写连接池,不仅仅适合Django
#utils文件夹下,创建redis_pool.py import redis POOL = redis.ConnectionPool(host=\'127.0.0.1\', port=6379,password=\'1234\',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(\'kkk\',\'age\',18) return HttpResponse(\'设置成功\') def order(request): conn = redis.Redis(connection_pool=POOL) conn.hget(\'kkk\',\'age\') return HttpResponse(\'获取成功\')