訊息釋出與訂閱頻道——redis
阿新 • • 發佈:2018-11-29
1. 釋出與訂閱頻道
訊息釋出與訂閱像收音機與廣播臺的關係
1.1. publish channel message 釋出頻道
語法:publish channel message
作用:釋出頻道訊息
返回值:訂閱數(類似粉絲數)
例:
127.0.0.1:6379> publish news 'today is sunday'
(integer) 0
1.2. subscribe channel [channel ...] 訂閱頻道
語法:subscribe channel [channel ...]
作用:訂閱頻道
例:
視窗1:
127.0.0.1:6379> publish news 'today is sunday'
(integer) 0
視窗2:
127.0.0.1:6379> subscribe news
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news"
3) (integer) 1
此時看不到視窗1已經發過的訊息,需要再發新訊息才能看到
視窗1:(再發)
127.0.0.1:6379> publish news 'still sunday'
(integer) 1
視窗2:(收到)
1) "message"
2) "news"
3) "still sunday"
如果再開幾個客戶端,同樣也能收到訊息
1.3. psubscribe pattern [pattern ...] 訂閱頻道
語法:psubscribe pattern [pattern ...]
作用:可以通過匹配模式來一次性訂閱多個頻道
例:
127.0.0.1:6379> psubscribe news*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "news*"
3) (integer) 1