Count number of messages in a JMS queue

后端 未结 3 1078
一个人的身影
一个人的身影 2021-02-05 10:51

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.

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 11:28

    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();
        }
    

提交回复
热议问题