Sunday 5 August 2018

JMS: Queue browser: filter the messages

This is continuation to my previous post. In my previous post, I explained, how can you scan a queue using QueueBrowser instance.

In this post, I am going to show you, how can you scan only the messages that you are interested in.

You can pass a message selector while creating QueueBrowser.
QueueBrowser createBrowser(Queue queue, String messageSelector)throws JMSException;

Example
QueueBrowser queueBrowser = session.createBrowser(orderQueue, "id % 2 = 0");

Above statement filters the messages, where the message id is an even number.

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);
   message.setIntProperty("id", i);
   producer.send(message);
  }

  QueueBrowser queueBrowser = session.createBrowser(orderQueue, "id % 2 = 0");

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

Output
Id                                                   data
ID:INLN50911363A-54668-1525260930364-1:1:1:1:2         OrderId2

ID:INLN50911363A-54668-1525260930364-1:1:1:1:4         OrderId4



Previous                                                 Next                                                 Home

No comments:

Post a Comment