1、先讲Python项目内可任意使用的redis,和框架无关
1.1 使用命令行安装redis模块
pip3 install redis
1.2 创建连接池并连接到redis,并设置最大连接数量
import redis
POOL = redis.ConnectionPool(host='XXX',port=XXX,password='XXX',max_connections=100,db=0,decode_responses=True)
conn = redis.Redis(connection_pool=POOL)
max_connections:最大连接数量
decode_responses: redis 取出的结果默认是字节,可以设定 decode_responses=True 改成字符串
1.3 存储key-value
conn.set('key1','23333',ex=3)
ex : ex - 过期时间(秒) 这里设置的过期时间是3秒,3秒后key1的值就变成None
1.4 获取key对应的值
print(conn.get('chenhaibing'))
#23333
2、使用django的django_redis模块
如果是在django项目里使用redis的话,也可以使用django_redis模型俩实现
2.1 安装django_redis
pip3 install django_redis
2.2 在settings文件里配置redis
代码:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://XXXXX",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {
"max_connections": 100, 'decode_responses': True},
"PASSWORD": "XXXXXXXX",
},
}
}
2.3 使用redis
from django_redis import get_redis_connection
conn = get_redis_connection()
conn.set('key1','233333',10)
b = conn.get('key1')
print(b)
#233333
第3个参数:10 代表是过期时间,10s