python操作redis实现发布订阅模式

  1. 发布者
import redis

pool = redis.ConnectionPool(host="xxxxx", port=6382, db=0, password="xxxxx")
r = redis.Redis(connection_pool=pool)

r.publish("my-first-channel", "first:哈哈哈")
r.publish("my-second-channel", "second:嘿嘿嘿")
r.publish("my-third-channel", "third:呵呵呵")
  1. 两个订阅者(两个线程)
import redis
from threading import Thread, current_thread

pool = redis.ConnectionPool(host="xxxxxx", port=6382, db=0, password="xxxxx")
r = redis.Redis(connection_pool=pool)


class PubSub(object):
    def __init__(self):
        self.pub = r.pubsub()

    def subscribe(self, *args):
        self.pub.subscribe(*args)
        self.pub.parse_response()
        self.pub.parse_response()
        return self.pub


def subscribe(p):
    while True:
        msg = p.parse_response()
        for i in msg:
            print(current_thread().name, i.decode(encoding="utf8"))


if __name__ == '__main__':

    # 开启一个订阅者
    t1 = Thread(target=subscribe, args=(PubSub().subscribe("my-first-channel", "my-second-channel"),))
    t1.start()

    # 开启第二个订阅者
    t2 = Thread(target=subscribe, args=(PubSub().subscribe("my-first-channel", "my-third-channel"),))
    t2.start()

    # 等待所有子线程结束,主线程在结束
    t1.join()
    t2.join()

官方文档-发布订阅

posted @ 2022-04-10 20:31  专职  阅读(284)  评论(0编辑  收藏  举报