一,消息的持久化和非持久化
①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
二,持久訂閱者和非持久訂閱者
①Durable Subscribers and NonDurable Subscribers
首先,持久訂閱者和非持久訂閱者針對的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.
②Durable Queues(Topics) and NonDurable Queues(Topics)