天天看點

Redis 釋出訂閱

Redis 釋出訂閱

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

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

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

Redis 釋出訂閱
當有新消息通過 PUBLISH 指令發送給頻道 channel1 時, 這個消息就會被發送給訂閱它的三個用戶端:

執行個體

redis 127.0.0.1:6379> SUBSCRIBE redisChat

Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3) (integer) 1      
redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"

(integer) 1

redis 127.0.0.1:6379> PUBLISH redisChat "Learn redis by runoob.com"

(integer) 1

# 訂閱者的用戶端會顯示如下消息
1) "message"
2) "redisChat"
3) "Redis is a great caching technique"
1) "message"
2) "redisChat"
3) "Learn redis by runoob.com"      

Redis 釋出訂閱指令

序号 指令及描述
1

PSUBSCRIBE pattern [pattern ...]

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

2

PUBSUB subcommand [argument [argument ...]]

檢視訂閱與釋出系統狀态。

3

PUBLISH channel message

将資訊發送到指定的頻道。

4

PUNSUBSCRIBE [pattern [pattern ...]]

退訂所有給定模式的頻道。

5

SUBSCRIBE channel [channel ...]

訂閱給定的一個或多個頻道的資訊。

6

UNSUBSCRIBE [channel [channel ...]]

指退訂給定的頻道。

繼續閱讀