统计JMS队列中的消息数量

18

什么是浏览JMS队列并获取其中所有消息的最佳方法?

如何计算队列中的消息数量?

谢谢。


1
在某些情况下(取决于JMS实现),您可以使用jmx。 - user1516873
我看到了 activemq 标签。ActiveMQ 的示例可以参考这篇文章:http://java.dzone.com/articles/managing-activemq-jmx-apis - user1516873
3个回答

15

使用JmsTemplate

public int getMessageCount(String messageSelector)
{
    return jmsTemplate.browseSelected(messageSelector, new BrowserCallback<Integer>() {
        @Override
        public Integer doInJms(Session s, QueueBrowser qb) throws JMSException
        {
            return Collections.list(qb.getEnumeration()).size();
        }
    });
}

2
为了完整起见:这是针对Spring框架用户的。 - Steffen Harbich
我发现一个问题,就是队列大小有时会返回0,这对于我们的使用情况来说会导致作业失败,不知道为什么,但是其他人在使用时是否也遇到了可靠性问题? - Zohaib Khan
我可以从JMSTemplate获取已出队的消息计数吗? - gifpif

8
这是如何计算队列中消息数量的方法。
public static void main(String[] args) throws Exception
    {
        // get the initial context
        InitialContext ctx = new InitialContext();

        // lookup the queue object
        Queue queue = (Queue) ctx.lookup("queue/queue0");

        // lookup the queue connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
            lookup("queue/connectionFactory");

        // create a queue connection
        QueueConnection queueConn = connFactory.createQueueConnection();

        // create a queue session
        QueueSession queueSession = queueConn.createQueueSession(false,
            Session.AUTO_ACKNOWLEDGE);

        // create a queue browser
        QueueBrowser queueBrowser = queueSession.createBrowser(queue);

        // start the connection
        queueConn.start();

        // browse the messages
        Enumeration e = queueBrowser.getEnumeration();
        int numMsgs = 0;

        // count number of messages
        while (e.hasMoreElements()) {
            Message message = (Message) e.nextElement();
            numMsgs++;
        }

        System.out.println(queue + " has " + numMsgs + " messages");

        // close the queue connection
        queueConn.close();
    }

我实际运行了这个示例,但不知何故消息计数显示为400,而我的队列中有5000条消息。 - Michael A
你如何表达一个队列中有5000条信息? - sunleo
我在我的ActiveMQ控制台上看到它的物理存在。 - Michael A
无论您是一次发送还是多次发送,都要检查ActiveMQ是否正在运行。如果需要多次尝试,请在检查之前确保ActiveMQ正在运行。 - sunleo
我的接收器接收到的消息数量与消息计数相同。 - Michael A
显示剩余4条评论

7

Java 8和Spring Boot

   public int countPendingMessages(String destination) {
    // to an Integer because the response of .browse may be null
    Integer totalPendingMessages = this.jmsTemplate.browse(destination, (session, browser) -> Collections.list(browser.getEnumeration()).size());

    return totalPendingMessages == null ? 0 : totalPendingMessages;
   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接