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

ActiveMQ Artemis JMS监听器无法消费队列消息求助

解决Spring JMS监听器无法消费ActiveMQ Artemis Topic消息的问题

问题分析与修复步骤

1. 让Spring管理ActiveMQServer的生命周期

当前activeMQServer()方法返回void,Spring无法识别这是需要管理生命周期的Bean,导致测试结束时服务器被立即关闭,消息还未被监听器消费就终止了。另外原代码中params.put("Schema", "tcp");的参数名错误(Artemis的Netty acceptor参数为小写schema),会导致 acceptor 配置不生效。

修改代码:

@Bean
public ActiveMQServer activeMQServer() throws Exception {
    Configuration configuration = new ConfigurationImpl();
    configuration.setPersistenceEnabled(false);
    configuration.setSecurityEnabled(false);

    Map<String, Object> params = new HashMap<>();
    params.put("host", "localhost");
    params.put("port", 61616);
    params.put("schema", "tcp"); // 修正参数名为小写schema
    TransportConfiguration transportConfiguration =
        new TransportConfiguration(
            NettyAcceptorFactory.class.getName(), params);

    configuration.setAcceptorConfigurations(
        Collections.singleton(transportConfiguration));

    CoreAddressConfiguration coreAddressConfiguration =
        new CoreAddressConfiguration();
    coreAddressConfiguration.setName(TOPIC_NAME)
        .addRoutingType(RoutingType.MULTICAST);
    configuration.addAddressConfiguration(coreAddressConfiguration);

    QueueConfiguration queueConfiguration =
        new QueueConfiguration(TOPIC_NAME);
    queueConfiguration.setAddress(TOPIC_NAME);
    queueConfiguration.setName(TOPIC_NAME);
    queueConfiguration.setRoutingType(RoutingType.MULTICAST);
    queueConfiguration.setDurable(true);
    configuration.addQueueConfiguration(queueConfiguration);

    ActiveMQServer server =
        ActiveMQServers.newActiveMQServer(configuration);
    server.start();
    return server; // 返回实例,让Spring管理生命周期
}

2. 配置JmsTemplate支持Topic模式

默认JmsTemplate工作在队列模式,发送Topic消息需要显式开启PubSubDomain:

修改JmsTemplate配置:

@Bean(name = "jmsTemplate")
public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setPubSubDomain(true); // 启用Topic模式
    return jmsTemplate;
}

3. 优化监听器的消息接收逻辑(可选)

将监听器参数改为消息体类型,方便直接查看内容,调试更直观:

@JmsListener(destination = "myTopic", containerFactory = "myFactory")
public void listener(String messageBody){
    System.out.println("Message received: " + messageBody);
}

修改后的测试验证

修改完成后,Spring会在上下文关闭前正确停止ActiveMQServer,给监听器足够时间处理消息。此时运行测试即可看到Message received的输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 15:18:22