Redis in Python: 發布訂閱__Python

來源:互聯網
上載者:User
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')


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.