2012-11-28 15 views
7

Qual è il modo migliore per passare una coda JMS e ottenere tutti i messaggi al suo interno?Contare il numero di messaggi in una coda JMS

Come può contare il numero di messaggi in una coda?

Grazie.

+1

È possibile utilizzare JMX in alcuni casi (a seconda di implementazione JMS) – user1516873

+0

vedo, 'ActiveMQ 'tag. Esempio per ActiveMQ http://java.dzone.com/articles/managing-activemq-jmx-apis – user1516873

risposta

6

Questo è come si può contare Numero di messaggi in una coda

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

Ho effettivamente eseguito questo esempio e per qualche motivo il conteggio dei messaggi mostra 400 quando ho 5000 messaggi in coda –

+0

come si dice hai 5000 messaggi in coda. – sunleo

+0

Lo vedo fisicamente sulla mia console ActiveMQ –

5

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