【Redis】Redis 發佈訂閱

Redis 發佈訂閱介紹

  Redis 發佈訂閱(pub/sub)是一種消息通訊模式:發送者(pub)發送消息,訂閱者(sub)接收消息。redis

  Redis 客戶端能夠訂閱任意數量的頻道。ui

  下圖展現了頻道 channel1 , 以及訂閱這個頻道的三個客戶端 —— client2 、 client5 和 client1 之間的關係:spa

    

  當有新消息經過 PUBLISH 命令發送給頻道 channel1 時, 這個消息就會被髮送給訂閱它的三個客戶端:code

    

實例

  如下實例演示了發佈訂閱是如何工做的。在實例中建立了訂閱頻道名爲 redisChat:blog

1 127.0.0.1:6379> SUBSCRIBE redisChat
2 Reading messages... (press Ctrl-C to quit)
3 1) "subscribe"
4 2) "redisChat"
5 3) (integer) 1

  如今,先從新開啓個 redis 客戶端,而後在同一個頻道 redisChat 發佈兩次消息,訂閱者就能接收到消息。it

1 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"
2 (integer) 1
3 127.0.0.1:6379> PUBLISH redisChat "Learn redis by runoob.com"
4 (integer) 1
1 # 訂閱者的客戶端會顯示以下消息
2 1) "message"
3 2) "redisChat"
4 3) "Redis is a great caching technique"
5 1) "message"
6 2) "redisChat"
7 3) "Learn redis by runoob.com"

Redis 發佈訂閱命令

  一、Redis Psubscribe 命令訂閱一個或多個符合給定模式的頻道。class

    每一個模式以 * 做爲匹配符,好比 it* 匹配全部以 it 開頭的頻道( it.news 、 it.blog 、 it.tweets 等等)。 news.* 匹配全部以 news. 開頭的頻道( news.it 、 news.global.today 等等),諸如此類。cli

    語法:PSUBSCRIBE pattern [pattern ...]語法

1 127.0.0.1:6379> PSUBSCRIBE mychannel
2 Reading messages... (press Ctrl-C to quit)
3 1) "psubscribe"
4 2) "mychannel"
5 3) (integer) 1

  二、Redis Pubsub 命令用於查看訂閱與發佈系統狀態,它由數個不一樣格式的子命令組成。channel

    語法:PUBSUB <subcommand> [argument [argument ...]]

1 127.0.0.1:6379> PUBSUB CHANNELS
2 (empty list or set)

  三、Redis Publish 命令用於將信息發送到指定的頻道。

    語法:PUBLISH channel message

1 127.0.0.1:6379> PUBLISH mychannel "hello, i m here"
2 (integer) 1

  四、Redis Punsubscribe 命令用於退訂全部給定模式的頻道。

    語法:PUNSUBSCRIBE [pattern [pattern ...]]

1 127.0.0.1:6379> PUNSUBSCRIBE mychannel 
2 1) "punsubscribe"
3 2) "mychannel"
4 3) (integer) 0

  五、Redis Subscribe 命令用於訂閱給定的一個或多個頻道的信息。

    語法:SUBSCRIBE channel [channel ...]

1 127.0.0.1:6379> SUBSCRIBE mychannel 
2 Reading messages... (press Ctrl-C to quit)
3 1) "subscribe"
4 2) "mychannel"
5 3) (integer) 1

   六、Redis Unsubscribe 命令用於退訂給定的一個或多個頻道的信息。

    語法:UNSUBSCRIBE channel [channel ...]

1 127.0.0.1:6379> UNSUBSCRIBE mychannel 
2 1) "unsubscribe"
3 2) "mychannel"
4 3) (integer) 0 
相關文章
相關標籤/搜索