分類
生產者消費模式
發布者訂閱模式
生產者消費模式
在生產者消費者(Producer/Consumer)模式下,上層應用接收到的外部請求后開始處理其當前步驟的操作,在執行完成后將已經完成的操作發送至指定的頻道(channel)當中,并由其下層的應用監聽該頻道并繼續下一步的操作,如果其處理完成后沒有下一步的操作就直接返回數據給外部請求,如果還有下一步的操作就再將任務發布到另外一個頻道,由另外一個消費者繼續監聽和處理。
模式介紹
生產者消費者模式下,多個消費者同時監聽一個隊里,但是一個消息只能被最先搶到消息的消費者消費,即消息任務是一次性讀取和處理,此模式在分布式業務架構中非常常用,比較常用的軟件還有RabbitMQ、Kafka、RocketMQ、ActiveMQ等
?隊列介紹
隊列當中的 消息由不同的生產者寫入也會有不同的消費者取出進行消費處理,但是一個消息一定是只能被取出一次也就是被消費一次
?生產者發布消息
127.0.0.1:6379> lrange channell 0 -1
1) "x2"
2) "x1"
127.0.0.1:6379> lpush channell x3
(integer) 3
127.0.0.1:6379> lpush channell x4
(integer) 4
127.0.0.1:6379> lpush channell x5
(integer) 5
查看隊列所有消息
127.0.0.1:6379> lrange channell 0 -1
1) "x5"
2) "x4"
3) "x3"
4) "x2"
5) "x1"
消費者消費消息
127.0.0.1:6379> rpop channell
"x1"
127.0.0.1:6379> rpop channell
"x2"
127.0.0.1:6379> rpop channell
"x3"
127.0.0.1:6379> rpop channell
"x4"
127.0.0.1:6379> rpop channell
"x5"
127.0.0.1:6379> rpop channell
(nil)
127.0.0.1:6379>
再次查看隊列消息
127.0.0.1:6379> lrange channell 0 -1
(empty array)
發布者訂閱模式
模式簡介
在發布者訂閱者模式下,發布者將消息發布到指定的channel里面,凡是監聽該channel的消費者都會收到同樣的一份消息,這種模式類似于是收音機的廣播模式,即凡是收聽某個頻道的聽眾都會收到主持人發布的相同的消息內容
此模式常用語群聊天、群通知、群公告等場景。
Subscriber:訂閱者
Publisher:發布者
Channel:頻道
?
?訂閱者監聽頻道
訂閱一個頻道
127.0.0.1:6379> subscribe channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
1) "message"訂閱多個頻道
127.0.0.1:6379> subscribe channel1 channel2
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
1) "subscribe"
2) "channel2"
3) (integer) 2訂閱匹配頻道
127.0.0.1:6379> psubscribe chann*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "chann*"
3) (integer) 1訂閱所有頻道
127.0.0.1:6379> psubscribe *
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "*"
3) (integer) 1
發布者發布消息
127.0.0.1:6379> publish channel1 test
(integer) 1
驗證消息
127.0.0.1:6379> subscribe channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
1) "message"
2) "channel1"
3) "test"