7.5. 使用消息拦截器
通过 AMQ 核心协议 JMS,您可以拦截进入或退出客户端的数据包,允许您审核数据包或过滤消息。拦截器可以更改它们拦截的数据包。这使得拦截器功能强大,同时也是您应该谨慎使用的功能。
拦截器必须实施 intercept() 方法,该方法返回 boolean 值。如果返回的值是 true,消息数据包将继续。如果返回的值是 false,则进程将被中止,不会调用其他拦截器,也不会进一步处理消息数据包。
消息拦截以透明的方式对主客户端代码发生,除非传出数据包以阻止发送模式发送。在发送传出数据包时,启用阻止并且数据包遇到返回 false 的拦截器时,会将 ActiveMQException 抛给调用者。抛出的异常包含拦截器的名称。
您的拦截器必须实现 org.apache.artemis.activemq.api.core.Interceptor 接口。客户端拦截器类及其依赖项必须添加到客户端的 Java 类路径中,以便能正确实例化和调用。
package com.example;
import org.apache.artemis.activemq.api.core.Interceptor;
import org.apache.activemq.artemis.core.protocol.core.Packet;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
public class MyInterceptor implements Interceptor {
private final int ACCEPTABLE_SIZE = 1024;
@Override
boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException {
int size = packet.getPacketSize();
if (size <= ACCEPTABLE_SIZE) {
System.out.println("This Packet has an acceptable size.");
return true;
}
return false;
}
}