Buscar en el Blog

martes, 23 de julio de 2013

Cómo crear un explorador de colas (QueueBrowser) para JMS

En ésta publicación, comparto el código Java para crear un explorador de colas JMS:
package com.blogspot.ingmmurillo.jms;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.junit.Test;
import javax.jms.*;
import java.util.Enumeration;

public class JMSQueueBrowser {

    @Test
    public void test() throws JMSException {
        System.out.println("Explorador de Colas JMS (QueueBrowser)");
        String url = "tcp://localhost:61717";                
        String queueName = "test";

        ConnectionFactory connectionFactory =
                new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();

        connection.start();

        System.out.println(connection.getMetaData().getJMSProviderName() + " JMS " +
                connection.getMetaData().getJMSVersion());

        QueueSession session = (QueueSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(queueName);
        QueueBrowser browser = session.createBrowser(queue);

        Enumeration e = browser.getEnumeration();

        if (e != null) {

            int i = 0;
            while (e.hasMoreElements()) {
                Object msg = e.nextElement();
                ActiveMQTextMessage m = (ActiveMQTextMessage) msg;
                System.out.println(m.getText());
                i++;

            }
            System.out.println("Nro. Mensajes: " + (i));
        }

        browser.close();
        session.close();
        connection.close();
    }

}

1 comentario: