Sunday, 5 August 2018

JMS: Queue Browser: Get all the items in a queue

Queue Browser instance is used to inspect the messages in a queue without removing them.

How can I create a Queue Browser instance?
A QueueBrowser can be created from a JMSContext, Session or QueueSession.

For example, Session interface provides below methods to get an instance of QueueBrowser.

QueueBrowser createBrowser(Queue queue) throws JMSException;
QueueBrowser createBrowser(Queue queue, String messageSelector)throws JMSException;

Below application write 5 messages to ‘ORDER_QUEUE’ and print them using QueueBrowser instance.

JMSProducer.java
package com.sample.producer;

import java.util.Enumeration;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JMSProducer {
 private static final String JMS_PROVIDER_URL = "tcp://127.0.0.1:5050";
 private static final String ORDER_QUEUE = "ORDER_QUEUE";

 public static void main(String[] args) throws JMSException, InterruptedException {
  ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(JMS_PROVIDER_URL);
  Connection connection = connectionFactory.createConnection();
  connection.start();

  Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

  Queue orderQueue = session.createQueue(ORDER_QUEUE);

  MessageProducer producer = session.createProducer(orderQueue);

  TextMessage message;

  for (int i = 1; i < 6; i++) {
   message = session.createTextMessage("OrderId" + i);
   producer.send(message);
  }

  QueueBrowser queueBrowser = session.createBrowser(orderQueue);

  Enumeration queueItems = queueBrowser.getEnumeration();

  System.out.println("Id\t\t\t\t\t\tdata");
  while (queueItems.hasMoreElements()) {
   TextMessage msg = (TextMessage) queueItems.nextElement();

   String data = msg.getText();
   String msgId = msg.getJMSMessageID();

   System.out.println(msgId + "\t" + data);
  }

  connection.close();
 }
}


Sample output
Id                                                   data
ID:INLN50911363A-54550-1525260347223-1:1:1:1:1         OrderId1
ID:INLN50911363A-54550-1525260347223-1:1:1:1:2         OrderId2
ID:INLN50911363A-54550-1525260347223-1:1:1:1:3         OrderId3
ID:INLN50911363A-54550-1525260347223-1:1:1:1:4         OrderId4
ID:INLN50911363A-54550-1525260347223-1:1:1:1:5         OrderId5




Previous                                                 Next                                                 Home

No comments:

Post a Comment