This example shows you how to send message to a JMS Topic, and subscribe them using selectors with JBoss Messaging, also creating 3 non durable subscribers. 2 subscriptions using selectors, and a third one that should receive the complete set of messages.
Topics and selectors are a standard part of JMS, please consult the JMS 1.1 specification for full details.
A regular subscriber would receive every message sent to the topic, but when you use a selector you would limit the messages you receive by the logic expression you choose only getting the messages that will matter to your processing.
To run the example, simply type ant
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();
}
}