You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在嵌入式ActiveMQ Artemis日志记录前执行数据转换?

ActiveMQ Artemis 日志前消息转换方案

要实现消息抵达服务器后、日志记录前的转换,你需要使用BrokerInterceptor,而非入站拦截器或Divert的Transformer,具体说明如下:

为什么现有方案不符合需求

  • 入站拦截器(remoting-incoming-interceptors):执行时机是消息从网络层进入服务器之前,还未进入Broker核心处理流程,不符合“抵达服务器后”的要求。
  • Divert Transformer:仅在消息被分流时触发,且分流操作位于Broker日志记录之后,因此转换会在日志生成后执行,不满足需求。

推荐方案:BrokerInterceptor

BrokerInterceptor是Broker核心处理链的一部分,其中beforeHandleMessage方法会在消息被Broker处理(包括日志记录)之前执行,完全匹配你的需求。

1. 实现BrokerInterceptor接口

自定义拦截器类,重写beforeHandleMessage方法完成转换逻辑:

import org.apache.activemq.artemis.core.server.BrokerInterceptor;
import org.apache.activemq.artemis.core.server.ServerSession;
import org.apache.activemq.artemis.core.server.MessageReference;

public class CustomBrokerInterceptor implements BrokerInterceptor {

    @Override
    public boolean beforeHandleMessage(ServerSession session, MessageReference reference) throws Exception {
        // 在这里执行消息转换操作
        var message = reference.getMessage();
        // 示例:修改消息属性或内容
        message.getBodyBuffer().writeString("transformed content");
        message.putStringProperty("processed", "true");
        
        // 返回true表示继续后续处理流程,返回false会中断消息处理
        return true;
    }

    @Override
    public void afterHandleMessage(ServerSession session, MessageReference reference, boolean succeeded) throws Exception {
        // 无需处理可留空,此方法为消息处理完成后的回调
    }
}

2. 配置拦截器

在broker.xml中添加Broker拦截器配置:

<broker-interceptors>
    <class-name>org.example.CustomBrokerInterceptor</class-name>
</broker-interceptors>

执行时机说明

Broker处理消息的核心流程顺序大致为:

  1. 入站拦截器(网络层接收后)
  2. BrokerInterceptor.beforeHandleMessage(此时消息已进入Broker核心,日志未生成)
  3. 消息日志记录
  4. 消息路由/分发/分流
  5. BrokerInterceptor.afterHandleMessage

因此beforeHandleMessage中的转换逻辑会严格执行在日志记录之前,满足你的需求。

内容的提问来源于stack exchange,提问作者Prabhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:42:47