Skip to content

Commit fab50b2

Browse files
committed
add python_redis.py
1 parent 45a4836 commit fab50b2

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@
5858

5959
### python_mail.py: 使用Python自动发送邮件,包括发送HTML以及图片、附件等
6060

61+
### python_redis.py: Python操作Redis实现消息的发布与订阅
62+
6163
### Plotly目录: 一些plotly画图的实例,使用jupyter notebook编写
6264
===================================================================================================
6365

python_redis.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# _*_ coding: utf-8 _*_
2+
3+
"""
4+
Python操作Redis实现消息的发布与订阅
5+
"""
6+
7+
import sys
8+
import time
9+
import redis
10+
11+
# 全局变量
12+
conn_pool = redis.ConnectionPool(host="localhost", port=6379, db=1)
13+
conn_inst = redis.Redis(connection_pool=conn_pool)
14+
channel_name = "fm-101.1"
15+
16+
17+
def public_test():
18+
while True:
19+
# 发布消息
20+
conn_inst.publish(channel_name, "hello " + str(time.time()))
21+
if int(time.time()) % 10 == 1:
22+
conn_inst.publish(channel_name, "over")
23+
time.sleep(1)
24+
25+
26+
def subscribe_test(_type=0):
27+
pub = conn_inst.pubsub()
28+
pub.subscribe(channel_name)
29+
30+
if _type == 0:
31+
# 订阅消息
32+
for item in pub.listen():
33+
print("Listen on channel: %s" % item)
34+
if item["type"] == "message" and item["data"].decode() == "over":
35+
print(item["channel"].decode(), "已停止发布")
36+
break
37+
else:
38+
# 另一种订阅模式
39+
while True:
40+
item = pub.parse_response()
41+
print("Listen on channel: %s" % item)
42+
if item[0].decode() == "message" and item[2].decode() == "over":
43+
print(item[1].decode(), "已停止发布")
44+
break
45+
46+
# 取消订阅
47+
pub.unsubscribe()
48+
return
49+
50+
51+
if __name__ == '__main__':
52+
if sys.argv[1] == "public":
53+
public_test()
54+
else:
55+
subscribe_test(int(sys.argv[2]))

0 commit comments

Comments
 (0)