Redis(4)- Redis与Python交互

Redis与Python的交互

1.redis-py的安装与使用

1.1.redis-py的安装

利用pip命令安装redis-py模块

pip install redis -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

redis-py模块官方主页

https://pypi.org/project/redis/

 

1.2.redis-py的使用

创建连接(基本不用这个)

1 import redis
2 r = redis.Redis(
3     host="localhost",
4     port=6379,
5     password="123456",
6     db=0
7 )

创建连接池

1 import redis
2 pool = redis.ConnectionPool(
3     host="localhost",
4     port=6379,
5     password="123456",
6     db=0,
7     max_connections=20
8 )

连接池中创建与关闭连接:

从连接池中获取的连接,不必关闭,垃圾回收的时候,连接会自动被归还到连接池

1 r = redis.Redis(
2     connection_pool=pool
3 )
4 #...
5 del r

 


2.redis-py中常用操作指令

redis各个数据类型操作的指令https://www.cnblogs.com/gltou/p/16230386.html;这边挑一些常用的记录一下,还可以去redis-py模块官网查,也有具体实例。

2.1.字符串数据类型操作指令

  • set:声明/添加字符e串
  • get:获取value
  • expire:设置超时
1 r.set("country","英国")   #创建字符串key:country,value:英国
2 r.set("city","伦敦")      #创建字符串key:city,value:伦敦
3 city=r.get("city").decode("utf-8")  #获取key:city的value值
4 print(city)     #伦敦

例子:

 1 r.set("country","英国")   #创建字符串key:country,value:英国
 2 r.set("city","伦敦")      #创建字符串key:city,value:伦敦
 3 city=r.get("city").decode("utf-8")  #获取key:city的value值
 4 print(city)     #伦敦
 5 
 6 r.expire("city",5)  #设置过期时间秒
 7 time.sleep(6)
 8 
 9 city=r.get("city").decode("utf-8")  #获取key:city的value值
10 print(city)
11 
12 """
13 Traceback (most recent call last):
14   File "D:/WorkSpace/Python_Study/python_redis/example_1.py", line 18, in <module>
15     city=r.get("city").decode("utf-8")  #获取key:city的value值
16 AttributeError: 'NoneType' object has no attribute 'decode'
17 
18 """
  • delete:删除记录,redis是del指令,redis-py模块提供了delete指令进行删除
  • mset:设置多个KEY_VALUE
  • mget:获得多个VALUE
1 r.delete("country","city")      #删除country和city
2 r.mset({"country":"德国","city":"柏林"})    #设置多个字符串,传入mset中必须是python字典的格式
3 result=r.mget("country","city")     #获得多个字符串内容,返回result是元组类型的
4 for one in result:
5     print(one.decode("utf-8"))

2.2.列表数据类型操作指令

  • rush:声明列表,列表右侧添加内容
  • lpop:删除列表左边的元素
  • lrange:输出列表内容
 1 from redis_db import pool
 2 import redis
 3 
 4 r=redis.Redis(
 5     connection_pool=pool
 6 )
 7 
 8 try:
 9     r.rpush("dname","董事会","秘书处","财务部","技术部")    #添加列表dname,向列表右侧添加内容
10     r.lpop("dname")     #删除列表最左侧内容
11     result=r.lrange("dname",0,-1)   #输出列表所有内容
12     for one in result:
13         print(one.decode("utf-8"))
14 except Exception as e:
15     print(e)
16 finally:
17     del r

2.3.集合数据类型操作指令

  • sadd:声明集合,添加内容
  • srem:删除集合元素
  • smembers:输出集合元素
 1 from redis_db import pool
 2 import redis
 3 r=redis.Redis(
 4     connection_pool=pool
 5 )
 6 
 7 try:
 8     r.sadd("employee",8001,8002,8003)   #声明集合,添加内容
 9     r.srem("employee",8001)             #删除集合8001元素
10     result=r.smembers("employee")       #返回集合所有元素
11     for one in result:
12         print(one.decode("utf-8"))
13 except Exception as e:
14     print(e)
15 finally:
16     del r

2.4.有序集合数据类型操作指令

  • zadd:声明有序集合,添加内容,元素和分值以字典形式传入zadd
  • zincrby:元素分值增加
  • zrevrange:降序输出结合元素
 1 from redis_db import pool
 2 import redis
 3 
 4 r=redis.Redis(
 5     connection_pool=pool
 6 )
 7 
 8 try:
 9     r.zadd("keyword",{"马云":0,"张朝阳":0,"丁磊":0})   #声明有序集合,添加内容
10     r.zincrby("keyword","10","马云")      #元素”马云“分值增加10
11     result=r.zrevrange("keyword",0,-1)  #倒序输出有序集合所有元素
12     for one in result:
13         print(one.decode("utf-8"))
14 except Exception as e:
15     print(e)
16 finally:
17     del r

 


3.redis-py中哈希类型数据与事务管理

3.1.哈希数据类型操作指定

注意一点,Redis 4.0.0开始弃用HMSET,虽然能用,但是会有警告,使用HSET

 

 

  • hmset:声明哈希类型数据,传入多个字段和值
  • hset:声明哈希类型数据,设置数据字段和值
  • hdel:删除哈希数据字段
  • hexists:判断哈希数据是否存在某个字段
  • hgetall:获得哈希数据所有的字段名
 1 from redis_db import pool
 2 import redis
 3 
 4 r=redis.Redis(
 5     connection_pool=pool
 6 )
 7 
 8 try:
 9     r.hmset("9527",{"name":"Scott","sex":"male","age":"35"})    #声明哈希类型数据9527,传入多个字段和值
10     r.hset("9527","city","纽约")  #设置数据字段和值
11     r.hdel("9527","age")    #删除哈希数据字段
12     print(r.hexists("9527", "name"))    #判断哈希数据是否存在某个字段
13     result=r.hgetall("9527")    #获得哈希数据所有的字段名
14     print(result)
15     for one in result:
16         print(one.decode("utf-8"),result[one].decode("utf-8"))
17 except Exception as e:
18     print(e)
19 finally:
20     del r

3.2.redis-py的事务函数

redis-py模块用pipeline(管道)的方式向Redis服务器传递批处理命令和执行事务

 1 from redis_db import pool
 2 import redis
 3 
 4 r=redis.Redis(
 5     connection_pool=pool
 6 )
 7 pipline=r.pipeline()    #创建pipeline对象
 8 pipline.watch(...)      #开启监视记录,传入你要监视的数据
 9 pipline.multi()         #开启事务
10 pipline.execute()       #提交事务
11 pipline.reset()         #关闭pipliner,让连接被回收

实例

 1 from redis_db import pool
 2 import redis
 3 
 4 r=redis.Redis(
 5     connection_pool=pool
 6 )
 7 
 8 try:
 9     pipline=r.pipeline()    #创建pipeline对象
10     pipline.watch("9527")      #开启监视记录,传入你要监视的数据
11     pipline.multi()         #开启事务
12     pipline.hset("9527","name","Jack")
13     pipline.hset("9527","age",23)
14     pipline.execute()       #提交事务
15 except Exception as e:
16     print(e)
17 finally:
18     if "pipline" in dir():
19         pipline.reset()     #关闭pipliner,让连接被回收
20     del r

 


4.练习

练习1

从TXT文档中解析学生的信息,把考试语数外成绩超过85分的同学信息,缓存到Redis的哈希表中

👇学生成绩

👇代码

 1 from redis_db import pool
 2 import redis
 3 
 4 r=redis.Redis(
 5     connection_pool=pool
 6 )
 7 
 8 try:
 9     with open("score.txt","r",encoding="utf-8") as f:
10         data=f.read().splitlines()
11     for line in data:
12         temp=line.split(",")
13         sid=temp[0]
14         name=temp[1]
15         classno=temp[2]
16         score_1=int(temp[3])
17         score_2=int(temp[4])
18         score_3=int(temp[5])
19         if score_1>=85 and score_2>=85 and score_3>=85:
20             r.hmset(sid,{"name":name,"classno":classno,"score_1":score_1,
21                            "score_2":score_2,"score_3":score_3})
22     print("执行成功")
23 except Exception as e:
24     print(e)
25 finally:
26     del r

👇检查

 

练习2

用Python程序模拟300位观众,为5位嘉宾(马云、丁磊、张朝阳、马化腾、李彦宏)随机投票,最后按照降序排列结果

 1 # coding:utf-8
 2 
 3 from redis_db import pool
 4 import redis,random
 5 
 6 r=redis.Redis(
 7     connection_pool=pool
 8 )
 9 
10 user=("马云","丁磊","张朝阳","马化腾","李彦宏")
11 j=0
12 try:
13     for i in range(len(user)):
14         r.zadd("match",{user[i]:0})
15     while True:
16         num = random.randint(0, len(user)-1)
17         if j<300:
18             r.zincrby("match",1,user[num])
19             j+=1
20         else:
21             break
22     result=r.zrevrange("match",0,-1,"WITHSCORES")
23     for one in result:
24         print(one[0].decode("utf-8"),int(one[1]))
25 except Exception as e:
26     print(e)
27 finally:
28     del r

 

练习3

👇前期知识回顾

 

👇需求

 1 # coding:utf-8
 2 
 3 from redis_db import pool
 4 import redis
 5 import random
 6 from concurrent.futures import ThreadPoolExecutor
 7 
 8 s=set()     #依据集合特性,创建集合存放抽奖用户ID
 9 while True:
10     if len(s)==1000:
11         break
12     num = random.randint(10000,100000)
13     s.add(num)
14 con = redis.Redis(
15     connection_pool=pool
16 )
17 try:
18     con.delete("kill_total","kill_num","kill_flag","kill_user")
19     con.set("kill_total",50)
20     con.set("kill_num",0)
21     con.set("kill_flag",1)
22     con.expire("kill_flag",600)
23 except Exception as e:
24     print(e)
25 finally:
26     del con
27 
28 executor=ThreadPoolExecutor(200)
29 
30 def buy():
31     connection=redis.Redis(
32         connection_pool=pool
33     )
34     pipline = connection.pipeline()
35     try:
36         if connection.exists("kill_flag")==1:
37             pipline.watch("kill_num","kill_user")
38             total=int(pipline.get("kill_total").decode("utf-8"))
39             num=int(pipline.get("kill_num").decode("utf-8"))
40             if num<total:
41                 pipline.multi()
42                 pipline.incr("kill_num")
43                 user_id=s.pop()
44                 pipline.rpush("kill_user",user_id)
45                 pipline.execute()
46     except Exception as e:
47         print(e)
48     finally:
49         if "pipline" in dir():
50             pipline.reset()
51         del connection
52 for i in range(0,1000):
53     executor.submit(buy)
54 
55 print("秒杀已经结束")

 

posted @ 2022-05-27 14:13  葛老头  阅读(130)  评论(0编辑  收藏  举报