Redis与Python的交互
驱动模块
- redis模块用来在Python环境下驱动Redis数据库
- 可以直接用pip方式安装
pip install redis
或者国内镜像下载:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
创建连接
import redis
con = redis.Redis(
host="localhost",
port="6379",
password="123456",
db=0
)
redis连接池
- 创建连接池
import redis
pool = redis.ConnectionPool(
host="localhost",
port="6379",
password="123456",
db=0
max_connection=20
)
- redis连接池操作完成后不需要关闭连接,用del删除连接对象后会自动归还到连接池
con = redis.Redis(
connection_pool=pool
)
......
del con
redis操作命令
- 字符串
con.set("country","中国")
con.set("city","上海)
city = con.get("city").decode('utf-8')
print(city)
con.delete("city")
con.mset("countyr":"中国","city":"上海")
result = con.mget("country","city")
for one in result:
print(one.decode('utf-8'))
- 哈希
con.hmset("86",{"country":"中国","city":"上海","code":"200000"})
con.hset("86","age":"70")
con.hdel("86","code")
con.hexists("86","city")
result = con.hgetall("86")
for one in result:
print(one.decode("utf-8"))
- 列表
con.rpush("courtry","中国","日本","韩国","印度")
con.lpop("country")
result = con.lrange("country",0,-1)
for one in result:
print(one.decode('utf-8'))
- 集合
con.sadd("courtry","中国","日本","韩国","印度")
con.rem("country","中国")
result = con.smembers("country")
for one in result:
print(one.decode('utf-8'))
- 有序集合
con.zadd("country",{"中国":"0","日本":"0","韩国":"0"})
con.zincrby("country","10","中国")
result = con.zrevrange("country",0,-1)
for one in result:
print(one.decode('utf-8'))
redis-py的事务函数
- redis-py模块用pipline(管道)的方式向redis服务器传递批处理命令和执行事务
pipline = con.pipline()
pipline.watch(......)
pipline.multi()
pipline.execute()
pipline.reset()
redis数据库异常处理和事务结合案例
import redis
pool = redis.ConnectionPool(
host="localhost",
port="6379",
password="123456",
db=0
max_connection=20
)
con = redis.Redis(
connection_pool=pool
)
pipline=con.pipline()
try:
pip.watch("country")
pip.multi()
pipline.zincrby("country","1","中国")
pipline.execute()
except Exception as e:
print(e)
finally:
if "pipline" in dir():
pipline.reset()
del con