Redis 发布与订阅
Redis 提供的发布与订阅命令
命令 | 用例和描述 |
---|---|
SUBSCRIBE | SUBSCRIBE channel [channel ...] —— 订阅给定的一个或多个频道 |
UNSUBSCRIBE | UNSUBSCRIBE [channel [channel ...]] —— 退订给定的频道,如果没有给定则退订所有 |
PUBLISH | PUBLISH channel message —— 向给定的频道发送消息 |
PSUBSCRIBE | PSUBSCRIBE pattern [pattern ...] —— 订阅与给定模式相匹配的所有频道 |
PUNSUBSCRIBE | PUNSUBSCRIBE [pattern [pattern ...]] —— 退订给定的模式,如果没有指定则退订所有 |
Python 示例 :
import time import threading import redis conn = redis.Redis() def publisher(n): time.sleep(1) for i in range(n): # 将消息发布到频道 conn.publish('channel', i) time.sleep(1) def run_pubsub(): threading.Thread(target=publisher, args=(3,)).start() pubsub = conn.pubsub() # 订阅频道 pubsub.subscribe(['channel']) count = 0 # 监听并打印消息 for item in pubsub.listen(): print(item) count += 1 if count == 4: pubsub.unsubscribe() if count == 5: break run_pubsub()
输出结果 :
{'channel': b'channel', 'data': 1, 'type': 'subscribe', 'pattern': None} {'channel': b'channel', 'data': b'0', 'type': 'message', 'pattern': None} {'channel': b'channel', 'data': b'1', 'type': 'message', 'pattern': None} {'channel': b'channel', 'data': b'2', 'type': 'message', 'pattern': None} {'channel': b'channel', 'data': 0, 'type': 'unsubscribe', 'pattern': None}