Publishing messages

When you publish a message, a copy is sent to all topic subscribers that have a message selector registered with the specified topic. Figure 3-3 illustrates the message flow when a client or component publishes a message.

Figure 3-3: Publish message flow

This example publishes a message that notifies clients of changes in a stock value; it creates the message text, creates a MessageProducer and the message using the Session object, then publishes the message:

public void notifyStockValue(Session mySession, 
                             Topic topic, 
                             String stock, 
                             double value)
{
   String text = time + ": The stock " + stock + " has value " + value;

   // Create the publisher and message objects.

   MessageProducer publisher = mySession.createProducer(topic);
   javax.jms.TextMessage textMsg = mySession.createTextMessage(text);

   
   // Publish a NON_PERSISTENT message with a priority of 9 and a 
   // time-to-live of 5000 milliseconds (5 seconds)

   publisher.publish(textMsg, DeliveryMode.NON_PERSISTENT, 9, 5000);
}

To publish a persistent message using the default priority (4) and timeout (never expires) values, use this syntax:

publisher.publish(textMsg);