驱动模块

  • 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

最新文章

  1. DDD实践问题之 - 关于论坛的帖子回复统计信息的更新的思考
  2. 成为java高手的条件
  3. python 3.5 关于sys问题总结
  4. winform 窗体传值
  5. [翻译]Shape comparison language
  6. JAVA学习<六>
  7. C# 将透明图片的非透明区域转换成Region
  8. 「linux」win+linux 双系统 默认启动项 的修改
  9. java7新特新(一) Try-with-resources (TWR)
  10. jsp bean标签
  11. 小学生之SpringMVC
  12. C语言错题小本子
  13. Message Queuing(MSMQ)
  14. Python Socket第二篇(socketserver)
  15. 【Android应用开发】Android Studio - MAC 版 - 快捷键详解
  16. StringBuffer/StringBuilder总结
  17. kubernets event 分析
  18. 性能测试 CentOS下结合InfluxDB及Grafana图表实时展示JMeter相关性能数据
  19. feign三:覆写feign的默认配置及feign的日志
  20. MySQL常见建表选项及约束

热门文章

  1. vscode添加vue文件模板
  2. son-server模拟http mock数据
  3. [转帖]Linux教程(13)- Linux中的通配符和正则表达式
  4. noip2019集训测试赛(二十一)Problem A: Colorful Balls
  5. 如何解决visual studio2017 install 下载安装极慢的问题
  6. 关于fastjson与jackson在反序列化bool型时的区别
  7. 启动mysql服务器
  8. Centos 7 替换镜像源
  9. IDEA使用@Data注解,类调用get、set方法标红的解决办法
  10. .NET子页Main页面实例(UI页面)