Redis 發佈訂閱消息對列實作(Python)

Redis pubsub, subscribe, listen, json.loads
# pip install redis
import redis
import json

r = redis.Redis(host="localhost", port=6379, db=1) # connect to redis

p = r.pubsub(ignore_subscribe_messages=True) # set pubsub to ignore_subscrible_messages true

p.subscribe('topic-1', 'topic-2') # subscrible a topic
p.psubscribe('topic-*') # or psubscrible, pattern mode  
for message in p.listen(): # listen what you just subscribed
    # message is a type of dict, including four keys , type, pattern, channel and data
    data = json.loads(message['data']) # extract data 
    print(type(data), data)

Redis publish, json.dumps
import redis
import json

db = redis.Redis(host="localhost", port=6379, db=1)
dict_data = {"name": "John", "gender": "male"}
json_data = json.dumps(dict_data)
db.publish("topic-1", json_data)

> {"name": "John", "gender": "male"}