1. 程式人生 > >Redis in Python: 釋出訂閱

Redis in Python: 釋出訂閱

Redis 釋出訂閱(pub/sub)是一種訊息通訊方式:釋出者(pub)傳送訊息,訂閱者(sub)接收訊息。

Redis 客戶端可以訂閱任意數量的頻道。

相關函式介紹:

0.publish

將資訊釋出到指定的頻道

1.subscribe

訂閱一個或者多個頻道

2.psubscribe

訂閱一個或多個符合特定模式的頻道

3.unsubscribe

退訂一個或多個頻道

4.punsubscribe

退訂一個或多個特定模式的頻道

例項:

釋出端: publish.py
import redis
import time

r = 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 redis

r = 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')