6.6.3. Publishing Messages to a Topic

6.6.3. Publishing Messages to a Topic

Publisher.java starts by creating a connection and a session, then creating a TextMessage object from the session. We will also create an exception listener to handle any JMS exceptions we receive:

Properties properties=new Properties();
properties.load(this.getClass().getResourceAsStream("pubsub.properties"));

//Create the initial context
Context ctx=new InitialContext(properties);

// Declare the connection factory, create a connection and a session
ConnectionFactory conFac=(ConnectionFactory) ctx.lookup("qpidConnectionfactory");
TopicConnection connection= (TopicConnection) conFac.createConnection();
TopicSession session=connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

Now we create a text message from the session:

message=session.createTextMessage();

To publish a message to a particular topic, we first look up the topic, then create a TopicPublisher and publish messages using it:

Topic topic = (Topic)ctx.lookup("usa.weather");
            
TopicPublisher messagePublisher=session.createPublisher(topic);            
publishMessages(message, messagePublisher);

The publishMessages() method simply publishes a series of messages:

private void publishMessages(TextMessage message, TopicPublisher messagePublisher) throws JMSException
{
    for (int i = 1; i < getNumberMessages() + 1; i++)
    {
        message.setText("Message " + i);
        messagePublisher
                .send(message, getDeliveryMode(), Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
    }
}

Now we send one final message to indicate termination:

 // send the final message
 message=session.createTextMessage("That's all, folks!");
 topic = (Topic)ctx.lookup("control");
 // Create a Message Publisher
 messagePublisher = session.createPublisher(topic);
 messagePublisher
         .send(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);

And close the connection and the JNDI context:

connection.close();
getInitialContext().close();