-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathredis_pub_sub.py
45 lines (31 loc) · 976 Bytes
/
redis_pub_sub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import redis
client = redis.Redis(host="localhost", port=6379)
def example_1():
pubsub = client.pubsub()
pubsub.subscribe("channel-1")
# use pattern subscribe
pubsub.psubscribe("channel-*")
print(pubsub.get_message())
print(pubsub.get_message())
print(client.publish("channel-1", "value-1"))
print(pubsub.get_message())
print(pubsub.get_message())
print("unsubscribe")
pubsub.unsubscribe("my")
pubsub.punsubscribe("my-*")
print(pubsub.get_message())
print(pubsub.get_message())
pubsub.close()
def my_handler(message):
print("MY HANDLER: ", message["data"])
def example_2():
pubsub = client.pubsub(ignore_subscribe_messages=False)
pubsub.subscribe(**{"my-channel": my_handler})
print(pubsub.get_message())
client.publish("my-channel", "awesome data")
pubsub.get_message()
pubsub.get_message()
pubsub.close()
# 可搭配 redis-cli MONITOR 觀察
example_1()
# example_2()