
examples.jms.topic.readme.html Maven / Gradle / Ivy
The newest version!
HornetQ JMS Topic Example
JMS Topic Example
This example shows you how to send and receive a message to a JMS Topic with HornetQ.
Topics are a standard part of JMS, please consult the JMS 1.1 specification for full details.
A Topic is used to send messages using the publish-subscribe model, from a producer to 1 or more consumers.
Example step-by-step
To run the example, simply type ./build.sh
(or build.bat
on windows) from this directory
- First we need to get an initial context so we can look-up the JMS connection factory and destination objects from JNDI. This initial context will get it's properties from the
client-jndi.properties
file in the directory ../common/config
InitialContext initialContext = getContext();
- We look-up the JMS topic object from JNDI
Topic topic = (Topic) initialContext.lookup("/topic/exampleTopic");
- We look-up the JMS connection factory object from JNDI
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
- We create a JMS connection
connection = cf.createConnection();
- We create a JMS session. The session is created as non transacted and will auto acknowledge messages.
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- We create a JMS message producer on the session. This will be used to send the messages.
MessageProducer messageProducer = session.createProducer(topic);
- We create a JMS Message Consumer, messageConsumer1, to receive the message.
MessageConsumer messageConsumer = session.createConsumer(topic);
- We create a JMS Message Consumer, messageConsumer2, to also receive the message.
MessageConsumer messageConsumer2 = session.createConsumer(topic);
- We create a JMS text message that we are going to send.
TextMessage message = session.createTextMessage("This is a text message");
- We send message to the topic
messageProducer.send(message);
- We start the connection. In order for delivery to occur on any consumers or subscribers on a connection, the connection must be started
connection.start();
- The message arrives at the first consumer
TextMessage messageReceived = (TextMessage) messageConsumer1.receive();
- The message arrives at the second consumer
messageReceived = (TextMessage) messageConsumer2.receive();
- And finally, always remember to close your JMS connections and resources after use, in a
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();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy