This example shows you how to selectively consume messages using message selectors with topic consumers.
Message selectors are strings with special syntax that can be used in creating consumers. Message consumers that are thus created only receive messages that match its selector. On message delivering, the ActiveMQ Server evaluates the corresponding message headers of the messages against each selector, if any, and then delivers the 'matched' messages to its consumer. Please consult the JMS 1.1 specification for full details.
In this example, three message consumers are created on a topic. The first consumer is created with selector
'color=red'
, it only receives messages that
have a 'color' string property of 'red' value; the second is created with selector 'color=green'
, it
only receives messages who have a 'color' string property of
'green' value; and the third without a selector, which means it receives all messages. To illustrate, three messages
with different 'color' property values are created and sent.
To run the example, simply type mvn verify
from this directory
client-jndi.properties
file in the directory ../common/config
InitialContext initialContext = getContext();
Topic topic = (Topic) initialContext.lookup("/topic/exampleTopic");
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(topic);
String redSelector = "color='red'";
String greenSelector = "color='green'";
MessageConsumer redConsumer = session.createConsumer(topic, redSelector);
redConsumer.setMessageListener(new SimpleMessageListener("red"));
MessageConsumer greenConsumer = session.createConsumer(topic, greenSelector);
greenConsumer.setMessageListener(new SimpleMessageListener("green"));
MessageConsumer allConsumer = session.createConsumer(topic);
allConsumer.setMessageListener(new SimpleMessageListener("all"));
TextMessage redMessage = session.createTextMessage("Red");
redMessage.setStringProperty("color", "red");
TextMessage greenMessage = session.createTextMessage("Green");
greenMessage.setStringProperty("color", "green");
TextMessage blueMessage = session.createTextMessage("Blue");
blueMessage.setStringProperty("color", "blue");
producer.send(redMessage);
System.out.println("Message sent: " + redMessage.getText());
producer.send(greenMessage);
System.out.println("Message sent: " + greenMessage.getText());
producer.send(blueMessage);
System.out.println("Message sent: " + blueMessage.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();
}
}