计数在JMS队列消息数(Count number of messages in a JMS queu

2019-08-03 07:04发布

什么是走在一个JMS队列,并得到它所有的信息最好的方法?

怎么能算的消息队列中的数字?

谢谢。

Answer 1:

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


Answer 2:

这是如何在一个队列计数无消息

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


文章来源: Count number of messages in a JMS queue