This example shows you how to use a JMS QueueBrowser with ActiveMQ.
Queues are a standard part of JMS, please consult the JMS 1.1 specification for full details.
A QueueBrowser is used to look at messages on the queue without removing them.
It can scan the entire content of a queue or only messages matching a message selector.
The example will send 2 messages on a queue, use a QueueBrowser to browse the queue (looking at the message without removing them) and finally consume the 2 messages
To run the example, simply type mvn verify -Pexample
from this directory
client-jndi.properties
file in the directory ../common/config
InitialContext initialContext = getContext();
Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(topic);
TextMessage message_1 = session.createTextMessage("this is the 1st message");
TextMessage message_2 = session.createTextMessage("this is the 2nd message");
messageProducer.send(message_1);
messageProducer.send(message_2);
QueueBrowser browser = session.createBrowser(queue);
Enumeration messageEnum = browser.getEnumeration();
while (messageEnum.hasMoreElements())
{
TextMessage message = (TextMessage)messageEnum.nextElement();
System.out.println("Browsing: " + message.getText());
}
browser.close();
The messages were browsed but they were not removed from the queue. We will now consume them.
MessageConsumer messageConsumer = session.createConsumer(queue);
connection.start();
TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000);
System.out.println("Received message: " + messageReceived.getText());
messageReceived = (TextMessage)messageConsumer.receive(5000);
System.out.println("Received message: " + messageReceived.getText());
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}