1. 程式人生 > 其它 >python操作redis實現釋出訂閱模式

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()

官方文件-釋出訂閱