Redis 的Pub(Publish)和Sub(Subscribe)即发布订阅功能。Pub/Sub是采用比较广泛的通信模型。采用事件作为通信机制,提供松散耦合的交互模式。
ps订阅方法:
subscribe - 订阅一个或多个频道
psubscribe - 订阅pattern匹配的频道(如:temppub* 订阅temppub开头的频道)
redis_pub.py发布demo
1 2 3 4 5 6 7 8 9 10
| import json
import redis
redis_con_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True, db=0) redis_con = redis.Redis(connection_pool=redis_con_pool)
redis_con.publish("temppub2", json.dumps({"test": "hhh2"})) redis_con.publish("temppub1", json.dumps({"test": "hhh"}))
|
redis_sub.py
1 2 3 4 5 6 7 8 9 10 11 12 13
| import redis
redis_con_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True, db=0) redis_con = redis.Redis(connection_pool=redis_con_pool)
ps = redis_con.pubsub() ps.subscribe(["temppub1", "temppub2"])
for item in ps.listen(): if item["type"] == "message": print(item["data"])
|