Redis 發布訂閱(pub/sub)是一種訊息通訊方式:發行者(pub)發送訊息,訂閱者(sub)接收訊息。
Redis 用戶端可以訂閱任意數量的頻道。
相關函數介紹: 0.publish
將資訊發布到指定的頻道 1.subscribe 訂閱一個或者多個頻道 2.psubscribe 訂閱一個或多個符合特定模式的頻道 3.unsubscribe 退訂一個或多個頻道 4.punsubscribe 退訂一個或多個特定模式的頻道
執行個體: 發布端: publish.py
import redisimport timer = redis.Redis()while True: time.sleep(1) r.publish('test1', 'hello') r.publish('test2', 'world') r.publish('foo', 'msg from foo') r.publish('foo1', 'msg from foo1') r.publish('foo2', 'msg from foo2') r.publish('bar', 'msg from bar') r.publish('bar2', 'msg from bar2') r.publish('bar3', 'msg from bar3') r.publish('foobar', 'msg from foobar') r.publish('foobar2', 'msg from foobar2') r.publish('foobar3', 'msg from foobar3')
訂閱端: subscribe.py
import redisr = redis.Redis()p = r.pubsub()p.subscribe(['test1', 'test2', 'test3'])p.psubscribe(['foo*', 'bar?', 'foobar+'])for item in p.listen(): if item['type'] == 'pmessage' or item['type'] == 'message': print(item['channel']) print(item['data'])
p.unsubscribe('test2')