安装redis-py模块 :
pip3 install redis -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
1. 创建连接
创建连接对象与线程池对象,最后封装连接池:
import redis
try:
pool = redis.ConnectionPool(
host='localhost',
port=6379,
#password='123456',
db=0,
max_connections=2000
)
except Exception as e:
print(e)
2.基本键值对管理
从连接池中获取连接、设置键值对、获取键值、设置键的过期时间以及删除键。
from redis_db import pool
import redis
#从连接池中获取一根连接,赋值跟conn
conn = redis.Redis(connection_pool=pool)
conn.set("country","中国")
conn.set("city","沈阳")
conn.set("s.country","日本")
country = conn.get("s.country").decode("utf-8")
# 30秒后销毁日本
conn.expire("s.country",30)
print(country)
#删除数据
conn.delete("city")
#删除连接
del conn
3.操作五种数据类型
初始化Redis连接:
from redis_db import pool
import redis
conn = redis.Redis(connection_pool=pool)