17

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

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

谢谢。

4

3 回答 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();
        }
    });
}
于 2017-02-28T18:47:24.393 回答
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();
    }
于 2012-11-28T11:33:31.740 回答
5

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;
   }
于 2020-01-08T08:51:16.750 回答