This example shows how messages can be consumed from a topic using Message Selectors.
Consumers (or Subscribers) will only consume messages routed to a topic that match the provided selector
Topics and selectors are a standard part of JMS, please consult the JMS 1.1 specification for full details.
To run the example, simply type mvn verify -Pexample
from this directory
client-jndi.properties
file in the directory ../common/config
initialContext = getContext();
Topic topic = (Topic) initialContext.lookup("/topic/exampleTopic");
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(topic);
MessageConsumer messageConsumer1 = session.createConsumer(topic, "someID=1", false);
MessageConsumer messageConsumer2 = session.createConsumer(topic, "someID=2", false);
MessageConsumer messageConsumer3 = session.createConsumer(topic, "someID=2", false);
for (int i = 1; i < 10; i++)
{
for (int someID = 1; someID <= 2; someID++)
{
TextMessage message1 = session.createTextMessage("This is a text message " + i +
" sent for someID=" +
someID);
message1.setIntProperty("someID", someID);
producer.send(message1);
System.out.println("Sent message: " + message1.getText());
}
}
connection.start();
for (;;)
{
TextMessage messageReceivedA = (TextMessage)messageConsumer1.receive(1000);
if (messageReceivedA == null)
{
break;
}
System.out.println("messageConsumer1 received " + messageReceivedA.getText() +
" someID = " +
messageReceivedA.getIntProperty("someID"));
}
for (;;)
{
TextMessage messageReceivedB = (TextMessage)messageConsumer2.receive(1000);
if (messageReceivedB == null)
{
break;
}
System.out.println("messageConsumer2 received " + messageReceivedB.getText() +
" someID = " +
messageReceivedB.getIntProperty("someID"));
}
for (;;)
{
TextMessage messageReceivedC = (TextMessage)messageConsumer3.receive(1000);
if (messageReceivedC == null)
{
break;
}
System.out.println("messageConsumer3 received " + messageReceivedC.getText() +
" someID = " +
messageReceivedC.getIntProperty("someID"));
}
subscriberA.close();
subscriberB.close();
session.unsubscribe("sub-a1");
session.unsubscribe("sub-a2");
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();
}
}