2012-11-28 183 views
7

通过JMS队列并获取所有消息的最佳方法是什么?统计JMS队列中的消息数

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

谢谢。

+1

你可以在某些情况下使用JMX(取决于JMS实现的) – user1516873

+0

我明白了,'的ActiveMQ '标签。 ActiveMQ的例子http://java.dzone.com/articles/managing-activemq-jmx-apis – user1516873

回答

6

这是你可以指望没有消息的队列中的

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

我实际上运行这个例子,由于某种原因,当我在队列上有5000条消息时,消息数显示为400 –

+0

How do you say队列中有5000条消息。 – sunleo

+0

我在我的ActiveMQ控制台 –

5

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