1. 程式人生 > >ActiveMQ中的訊息的持久化和非持久化 以及 持久訂閱者 和 非持久訂閱者之間的區別與聯絡

ActiveMQ中的訊息的持久化和非持久化 以及 持久訂閱者 和 非持久訂閱者之間的區別與聯絡

①DeliveryMode

這是傳輸模式。ActiveMQ支援兩種傳輸模式:持久傳輸和非持久傳輸(persistent and non-persistent delivery),預設情況下使用的是持久傳輸。

可以通過MessageProducer類的 setDeliveryMode方法設定傳輸模式

MessageProducer producer = ...;
producer.setDeliveryMode(DeliveryMode.PERSISTENT);

持久傳輸和非持久傳輸最大的區別是:採用持久傳輸時,傳輸的訊息會儲存到磁碟中(messages are persisted to disk/database),即“儲存轉發”方式。先把訊息儲存到磁碟中,然後再將訊息“轉發”給訂閱者。

採用非持久傳輸時,傳送的訊息儲存到磁碟中。

採用持久傳輸時,當Borker宕機 恢復後,訊息還在。採用非持久傳輸,Borker宕機重啟後,訊息丟失。比如,當生產者將訊息投遞給Broker後,Broker將該訊息儲存到磁碟中,在Broker將訊息傳送給Subscriber之前,Broker宕機了,如果採用持久傳輸,Broker重啟後,從磁碟中讀出訊息再傳遞給Subscriber;如果採用非持久傳輸,這條訊息就丟失了。

關於傳輸模式的官方文件,可參考

關於Message Durability 和 Message Persistence的區別:我是在《ActiveMQ in Action》中看到的,理解如下:

②Message Persistence

Message persistence is independent of the message domain. 
It is used to indicate the JMS application's ability to handle missing messages in the event of a JMS provider failure. 

這說明:1)Message Persistence 與Domain無關。 2)Message persistence 與傳輸模式有關,如果某訊息 使用的是持久傳輸,則該訊息具有 Persistence性質,否則不是。

到這裡為止,已經知道若ActiveMQ採用持久傳輸模式,則會把訊息持久化到磁碟中。那麼,訊息是以何種形式儲存的呢?是儲存到檔案中還是儲存到資料庫中? 儲存的資料結構如何實現?是B樹還是其他?…… 關於這些問題都是很直接值得研究的。關於訊息持久化內容,可簡單參考

③Durability of messages(Message Durability)

Message durability can only be achieved with the pub/sub domain.
When clients connect to a topic, they can do so using a durable or a non-durable subscription.

以上說明了兩點:1)Durability of messages 只針對釋出訂閱模型(Domain)。 2)持久訂閱和非持久訂閱是針對Topic而言的,不是針對Queue的

也就是說,如果某個訊息被持久訂閱者訂閱了,那麼該訊息就具有:Durability,否則就是NonDurability

二,持久訂閱者和非持久訂閱者

首先,持久訂閱者和非持久訂閱者針對的Domain是Pub/Sub,而不是P2P

當Broker傳送訊息給訂閱者時,如果訂閱者處於 inactive 狀態持久訂閱者可以收到訊息,而非持久訂閱者則收不到訊息。

類似於QQ訊息,別人給你發了離線訊息,如果是非持久訂閱者 就收到不離線訊息。

造成的影響是:當持久訂閱者處於 inactive 狀態時,Broker需要為持久訂閱者儲存訊息,如果持久訂閱者訂閱的訊息太多則會溢位。(當訊息投遞成功之後,Broker就可以把訊息刪除了)

一個具體的官方例項如下:

複製程式碼
For example imagine a durable subscriber S starts up subscribing to topic T at time D1. 
Some publisher sends messages M1, M2, M3 to the topic and S will receive each of these messages. 
Then S is stopped and the publisher continues to send M4, M5.
When S restarts at D2, the publisher sends M6 and M7. 
Now S will receive M4, M5 followed by M6 and M7 and all future messages. i.e. S will receive all messages from M1..M7.

This is the difference between durable and non-durable consuming.
 If S were a non-durable consumer then it would only have received M1, M2, M3 and M6, M7 - not M4 and M5.
 i.e. because the subscription is durable, S will receive every message sent to T whether the subscriber is running or not.
 For non-durable topics, only messages delivered to the topic T when S is running are delivered.
複製程式碼

總結

   持久訂閱者/非持久訂閱者,隻影響離線的時候訊息(包括持久訊息和非持久訊息)是否能接收到,和訊息是否持久無關;持久訊息/非持久訊息,只是影響jms provider宕機後。訊息是否會丟失,如果永遠不會宕機,那麼持久訊息和非持久訊息沒有區別。