Tuesday, February 3, 2009

Unidentified Message Producer

The JMS Session is the factory to create message producers. When creating a message producer, the Session's create producer method parameter specifies a Destination object to be associated with the producer created.

The method in the Session API to create a message producer is as follows.
MessageProducer createProducer(Destination destination) throws JMSException;
If a non-null destination is specified in the parameter, the created message producer is called an identified message producer. An identified message producer is used when a producer always produces messages to the same destination during the life time of the producer object.

If a null destination is specified in the parameter, the created message producer is called an unidentified message producer. An unidentified message producer is used when a producer is used to produce messages to more than one destinations. For example, the following is an example to use an unidentified message producer. The send method in the code snippet sends a message to a queue or topic destination. The JMS objects are initialize (in the init() method) before the send method is invoked.

* Initialize JMS objects.
* @throws JMSException
public void init() throws JMSException {

//get an instance of JMS connection factory.
ConnectionFactory factory = EMFactory.getConnectionFactory();

//create a connection
conn = factory.createConnection();

//create a session
session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

//create a message producer on the destination
producer = session.createProducer(null);

myTopic = session.createTopic("myTopic");

myQueue = session.createQueue("myQueue");

* The send example method sends a message to a queue or topic based
* on the specified boolean parameter.
* @param sendToTopic true if the message is to be sent to topic
* destination. Otherwise, the message is sent to a queue destination.
* @param text The text message to be set in the text message.
* @throws JMSException if any internal error occurred.
public void send(boolean sendToTopic, String text) throws JMSException {

// destination
Destination dest = null;

// create a queue instance
if (sendToTopic) {
dest = myTopic;
} else {
dest = myQueue;

// create a text message
TextMessage m = session.createTextMessage(text);

System.out.println("sending message to destination:\n " + dest);

// send the ping message
producer.send(dest, m);

An unidentified message producer is often used as a cached producer. Applications would get an instance of an unidentified message producer object from its cache implementation before sending a message. In this scenario, it is required to synchronize the usage of a cached producer. The messaging service behavior is undefined if a session (producer object) usage is not synchronized.

No comments:

Post a Comment