首页 > Java > java教程 > 正文

ActiveMQ Artemis:解决通过选择器浏览消息成功但无法消费的问题

花韻仙語
发布: 2025-11-05 22:32:01
原创
471人浏览过

ActiveMQ Artemis:解决通过选择器浏览消息成功但无法消费的问题

本教程深入探讨了activemq artemis 2.18.0版本中一个特定且棘手的问题:当使用jms选择器可以成功浏览消息,但尝试通过messageconsumer接收同一条消息时却失败。文章揭示了该问题通常与openwire jms客户端协议以及artemis-3916缺陷有关,并提供了两种核心解决方案:切换至activemq artemis原生核心jms客户端,或将broker升级至2.25.0及以上版本,以确保消息的可靠消费。

ActiveMQ Artemis消息消费的困境

在ActiveMQ Artemis 2.18.0环境中,开发者有时会遇到一个令人困惑的现象:通过JMS选择器(例如,基于JMSMessageID)可以成功地使用QueueBrowser浏览队列中的特定消息,确认消息确实存在且选择器有效。然而,当随后使用MessageConsumer尝试通过相同的选择器接收这条消息时,receive()方法却可能返回null,甚至在某些实现中抛出IllegalStateException,表明无法获取到预期的消息。这种问题通常表现出间歇性,增加了诊断的难度。

以下是一个简化的问题代码结构,它展示了这种浏览成功但消费失败的场景:

import javax.jms.*;
import java.util.Enumeration;

public class ProblematicMessageConsumptionExample {
    // 假设 activeMQJMSConnectionFactory 已经初始化,指向 Artemis Broker
    private ConnectionFactory activeMQJMSConnectionFactory; 

    public void demonstrateProblem(String messageId) {
        Connection connection = null;
        Session session = null;
        String selector = "JMSMessageID='" + messageId + "'";
        try {
            connection = activeMQJMSConnectionFactory.createConnection();
            session = connection.createSession(true, Session.SESSION_TRANSACTED);
            Queue deadQueue = session.createQueue("hospital");
            connection.start();

            // 步骤1: 浏览消息 - 预期成功找到一条消息
            QueueBrowser browser = session.createBrowser(deadQueue, selector);
            Enumeration<?> e = browser.getEnumeration();
            int foundedElements = 0;
            while (e.hasMoreElements()) {
                Message message = (Message) e.nextElement();
                System.out.println("Browser found message with ID: " + message.getJMSMessageID());
                foundedElements++;
            }
            browser.close();

            if (foundedElements != 1) {
                throw new IllegalStateException("Browser did not find exactly one message for selector: " + selector);
            }
            System.out.println("Browser successfully found " + foundedElements + " message(s).");

            // 步骤2: 消费消息 - 在某些情况下,receive()会返回null,导致异常
            MessageConsumer messageConsumer = session.createConsumer(deadQueue, selector);
            Message received = messageConsumer.receive(1000); // 设置超时1秒
            if (received == null) {
                // *** 问题通常发生在这里:receive()返回null ***
                throw new IllegalStateException("MessageConsumer.receive() returned null for selector: " + selector);
            }
            System.out.println("Consumer successfully received message with ID: " + received.getJMSMessageID());
            messageConsumer.close();

            session.commit(); // 提交事务
            session.close();
        } catch (Exception e) {
            System.err.println("An error occurred during message processing: " + e.getMessage());
            try {
                if (session != null) {
                    session.rollback(); // 回滚事务
                    session.close();
                }
            } catch (JMSException e1) {
                e1.printStackTrace();
            }
            throw new RuntimeException(e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    throw new RuntimeException("Failed to close connection", e);
                }
            }
        }
    }
}
登录后复制

问题根源:OpenWire客户端与ARTEMIS-3916

经过深入分析,该问题通常与客户端使用的JMS库及其底层协议密切相关。在ActiveMQ Artemis 2.18.0版本中,当客户端通过OpenWire JMS协议连接到Broker时,会触发一个已知的缺陷:ARTEMIS-3916

ARTEMIS-3916是一个特定于OpenWire协议的错误,它可能导致Broker在处理带有选择器的消息消费请求时出现内部逻辑问题,使得即使队列中存在匹配选择器的消息,MessageConsumer也无法正确地将其传递给客户端。这解释了为什么QueueBrowser能够“看到”消息(因为它只是查询消息元数据),而MessageConsumer却无法“获取”消息(因为它涉及更复杂的消费逻辑和消息锁定)。

值得注意的是,如果客户端使用的是ActiveMQ Artemis的原生核心JMS客户端协议,此问题通常不会发生,这进一步证实了问题在于OpenWire协议的兼容性层。

AI卡通生成器
AI卡通生成器

免费在线AI卡通图片生成器 | 一键将图片或文本转换成精美卡通形象

AI卡通生成器 51
查看详情 AI卡通生成器

解决方案

解决此问题主要有两种策略,它们分别从客户端和服务端入手:

方案一:确保使用ActiveMQ Artemis核心JMS客户端

这是推荐的首选方案。ActiveMQ Artemis拥有其专为高性能和稳定性设计的原生核心JMS客户端和协议。避免使用OpenWire协议可以绕过ARTEMIS-3916缺陷。

实现方法:

  1. 检查并调整Maven/Gradle依赖: 确保您的项目依赖于ActiveMQ Artemis的官方JMS客户端库,例如 org.apache.activemq.artemis:artemis-jms-client 或 org.apache.activemq.artemis:artemis-jms-client-all。避免引入旧版Apache ActiveMQ的OpenWire客户端依赖(如org.apache.activemq:activemq-client),除非您确实需要与旧版ActiveMQ Broker兼容。

    <!-- Maven 示例:确保使用 Artemis 客户端 -->
    <dependency>
        <groupId>org.apache.activemq.artemis</groupId>
        <artifactId>artemis-jms-client</artifactId>
        <version>2.18.0</version> <!-- 或更高版本,与您的Broker版本匹配 -->
    </dependency>
    <!-- 如果您需要所有功能,也可以使用 artemis-jms-client-all -->
    <!--
    <dependency>
        <groupId>org.apache.activemq.artemis</groupId>
        <artifactId>artemis-jms-client-all</artifactId>
        <version>2.18.0</version>
    </dependency>
    -->
    登录后复制
  2. 使用ActiveMQ Artemis的ConnectionFactory: 在代码中,确保您使用的是 org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory 来创建连接。该工厂默认使用Artemis的核心协议。

    import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory;
    import javax.jms.*;
    import java.util.Enumeration;
    
    public class ArtemisCoreClientSolution {
        private static final String BROKER_URL = "tcp://localhost:61616"; // Artemis Core Protocol 默认端口
    
        public static void main(String[] args) throws Exception {
            // 使用 ActiveMQJMSConnectionFactory 确保使用核心协议
            ConnectionFactory connectionFactory = new ActiveMQJMSConnectionFactory(BROKER_URL);
    
            try (Connection connection = connectionFactory.createConnection()) {
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
                Queue testQueue = session.createQueue("hospital");
                connection.start();
    
                // 1. 发送一条消息用于测试
                MessageProducer producer = session.createProducer(testQueue);
                TextMessage sentMessage = session.createTextMessage("This is a test message for consumption.");
                producer.send(sentMessage);
                session.commit(); // 提交发送事务
                System.out.println("Sent message with ID: " + sentMessage.getJMSMessageID());
    
                String selector = "JMSMessageID='" + sentMessage.getJMSMessageID() + "'";
                System.out.println("Using selector: " + selector);
    
                // 2. 浏览消息
                QueueBrowser browser = session.createBrowser(testQueue, selector);
                Enumeration<?> e = browser.getEnumeration();
                int foundedElements = 0;
                while (e.hasMoreElements()) {
                    Message msg = (Message) e.nextElement();
                    System.out.println("Browser found message: " + msg.getJMSMessageID());
                    foundedElements++;
                }
                browser.close();
    
                if (foundedElements != 1) {
                    throw new IllegalStateException("Browser did not find exactly one message.");
                }
                System.out.println("Browser successfully found " + foundedElements + " message(s).");
    
                // 3. 消费消息
                MessageConsumer consumer = session.createConsumer(testQueue, selector);
                Message receivedMessage = consumer.receive(5000); // 增加超时时间以确保有足够时间接收
                if (receivedMessage == null) {
                    throw new IllegalStateException("MessageConsumer.receive() returned null unexpectedly!");
                } else if (!(receivedMessage instanceof TextMessage) || !((TextMessage) receivedMessage).getText().equals(sentMessage.getText())) {
                    throw new IllegalStateException("Received message content mismatch.");
                }
                System.out.println("Consumer successfully received message with ID: " + receivedMessage.getJMSMessageID());
                consumer.close();
                session.commit(); // 提交接收事务
                System.out.println("Message successfully browsed and consumed using Artemis Core Client.");
    
            } catch (Exception e) {
                System.err.println("An error occurred: " + e.getMessage());
                throw e;
            }
        }
    }
    登录后复制

方案二:升级ActiveMQ Artemis Broker

ARTEMIS-3916缺陷已在后续的ActiveMQ Artemis版本中得到修复。因此,升级Broker是解决此问题的最彻底方法。

以上就是ActiveMQ Artemis:解决通过选择器浏览消息成功但无法消费的问题的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号