18

What is the best way to go over a JMS queue and get all the messages in it?

How can count the number of messages in a queue?

Thanks.

Wernsey
  • 5,411
  • 22
  • 38
Michael A
  • 5,770
  • 16
  • 75
  • 127

3 Answers3

15

Using 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();
        }
    });
}
Aaron G.
  • 377
  • 3
  • 6
8

This is how you can count No of Messages in a Queue

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();
    }
Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
sunleo
  • 10,589
  • 35
  • 116
  • 196
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;
   }
MevlütÖzdemir
  • 3,180
  • 1
  • 23
  • 28