Monday, May 14, 2012

Sending a Message to Queue (JMS Way)

There are thousand confusing ways to send a message to queue and every method looks correct and perfect for production implemetation.
Below is simple method which is used most of the time and also JMS API Complient. Benefit of using JMS Complient provider is: your code will remain unchanged even if provider changes.  But yes, you have to make sure about you exception handling mechanism and your queue access.

Steps are explained below:
1. Get the ConnectionFactory from JNDI
2. Create Connection from Connection Factory
3. Get the destination from JNDI or Create Destination
3. Create a Session from Connection
4. Create a Message Producer from Session using Destination
5. Create a Message from Session
6. Send the message using message producer.
7. Close the mess.
8. Check the queue depth - Not in Java (using queue browsing tools)



package com.xyz;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class SampleMessageSender
{
private String jndiQCFName = null;
private ConnectionFactory factory = null;
public SampleMessageSender(String jndiQCFName){
this.jndiQCFName = jndiQCFName;
}
public void sendMessage(String jndiDestination, String messagePayload)
throws NamingException
{
InitialContext context = null;
MessageProducer producer =  null;
Connection connection = null;
Session session = null;
try
{
context = new InitialContext();
factory = (ConnectionFactory) context.lookup("java:comp/env/"+jndiQCFName);
Destination destination = (Destination) context.lookup("java:comp/env/"+jndiDestination);
connection = factory.createConnection();
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
// Create a Producer for this Destination
producer = session.createProducer(destination);
// Create a Message from Payload
Message message = session.createTextMessage(messagePayload);
// Send the message
producer.send(message);
}
catch(JMSException exe)
{
exe.printStackTrace();
// Do logging
if(exe.getLinkedException() != null){
// Linked exception may have provider specific details. Log it.
exe.getLinkedException().printStackTrace();
}
}
finally{
context.close();
try {
producer.close();
session.close();
connection.close();
} catch (JMSException e) {
// Nothing can be done here
e.printStackTrace();
}
}
}
}

No comments:

Post a Comment