Apache ActiveMQ Artemis 支援攔截器來攔截進入和離開伺服器的封包。進入和離開的攔截器會分別針對任何進入或離開伺服器的封包被呼叫。這允許執行自訂程式碼,例如用於稽核封包、過濾或其他原因。攔截器可以變更它們攔截的封包。這使得攔截器功能強大,但也可能很危險。
1. 實作攔截器
所有攔截器都是特定於協定的。
核心協定的攔截器必須實作 Interceptor
介面
package org.apache.activemq.artemis.api.core.interceptor;
public interface Interceptor {
boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException;
}
對於 stomp 協定,攔截器必須實作 StompFrameInterceptor
介面
package org.apache.activemq.artemis.core.protocol.stomp;
public interface StompFrameInterceptor extends BaseInterceptor<StompFrame> {
boolean intercept(StompFrame stompFrame, RemotingConnection connection);
}
同樣地,對於 MQTT 協定,攔截器必須實作 MQTTInterceptor
介面
package org.apache.activemq.artemis.core.protocol.mqtt;
public interface MQTTInterceptor extends BaseInterceptor<MqttMessage> {
boolean intercept(MqttMessage mqttMessage, RemotingConnection connection);
}
傳回的布林值很重要
-
如果傳回
true
,則程序會正常繼續 -
如果傳回
false
,則程序會中止,不會呼叫其他攔截器,且伺服器將不會進一步處理封包。
2. 設定攔截器
進入和離開的攔截器都在 broker.xml
中設定
<remoting-incoming-interceptors>
<class-name>org.apache.activemq.artemis.jms.example.LoginInterceptor</class-name>
<class-name>org.apache.activemq.artemis.jms.example.AdditionalPropertyInterceptor</class-name>
</remoting-incoming-interceptors>
<remoting-outgoing-interceptors>
<class-name>org.apache.activemq.artemis.jms.example.LogoutInterceptor</class-name>
<class-name>org.apache.activemq.artemis.jms.example.AdditionalPropertyInterceptor</class-name>
</remoting-outgoing-interceptors>
請參閱關於新增執行階段相依性的文件,以了解如何使您的攔截器可供代理程式使用。
3. 用戶端上的攔截器
攔截器也可以在 Apache ActiveMQ Artemis 用戶端執行,以攔截用戶端傳送至伺服器或伺服器傳送至用戶端的封包。這是透過使用 addIncomingInterceptor(Interceptor)
或 addOutgoingInterceptor(Interceptor)
方法將攔截器新增至 ServerLocator
來完成的。
如上所述,如果攔截器傳回 false
,則封包的傳送會中止,這表示不會呼叫其他攔截器,且用戶端不會進一步處理封包。通常,此程序對於用戶端而言是透明的(也就是說,它不知道封包是否已中止)。但是,在以 blocking
方式傳送的傳出封包的情況下,將會向呼叫者擲回 ActiveMQException
。之所以擲回例外,是因為阻塞式傳送提供可靠性,並且認為它們不成功是一種錯誤。例如,當應用程式在其 ServerLocator
上叫用 setBlockOnNonDurableSend(true)
或 setBlockOnDurableSend(true)
,或者當應用程式正在使用從 JNDI 擷取的 JMS 連接器工廠,而該工廠已將 block-on-durable-send
或 block-on-non-durable-send
設定為 true
時,就會發生阻塞式
傳送。阻塞式也用於處理交易的封包(例如,提交、回滾等)。擲回的 ActiveMQException
將包含傳回 false 的攔截器的名稱。
如同在伺服器上,用戶端攔截器類別(及其相依性)必須新增至類別路徑,才能正確地實例化和叫用。