The following code snippet illustrates how to set up the JMS framework for sending and receiving messages. Notice how the code follows the steps outlined in The Java Message Service. Most applications, naturally, will only create a QueueReceiver or a QueueSender (or TopicPublisher or a TopicSubscriber for pub/sub). JMS has a transaction framework of its own, and you can specify transaction handling when creating a Session. Here, and in the example application for this section, the code specifies false, meaning that no transactions are used. The Session.AUTO_ACKNOWLEDGE argument specifies automatic acknowledgement of the message when the onMessage() method completes. If the message is not acknowledged, it will be resent. You should be aware that the transactional mode can have a major impact on quality of service (QoS) and guaranteed delivery of messages. For more information about JMS transactions, see Resources.
If a QueueConnection calls start() to begin receiving incoming messages, QueueConnection.stop() should be called before exiting the application. QueueConnection.close() should always be called prior to exit to conserve resources. Pub/sub programs look very similar to the following code, the primary difference being that Topic objects are used rather than Queue objects.
import javax.jms.*;
import javax.naming.*;
public class XXX implements MessageListener
{
InitialContext ic;
Queue q;
QueueConnection qc;
QueueConnectionFactory qcf;
QueueReceiver qReceiver;
QueueSender qSender;
QueueSession qSession;
TextMessage tm;
public void setupJMS( String sQueueConnectionFactoryName,
String sQueueName )
{
try
{
// lookup the JMS driver and queue
ic = new InitialContext();
qcf = (QueueConnectionFactory)initContext.lookup(
"java:comp/env/jms/" +
sQueueConnectionFactoryName );
q = (Queue)initContext.lookup(
"java:comp/env/jms/" + sQueueName );
// create the necessary JMS objects
qc = qcf.createQueueConnection();
qSession = qc.createQueueSession(
false, Session.AUTO_ACKNOWLEDGE );
// create the sender
qSender = session.createSender( q );
// create the receiver
qReceiver = qSession.createReceiver( q );
qReceiver.setMessageListener( this );
qc.start();
}
...
} // end setupJMS
public void sendMsg( String sMsgText )
{
try
{
tm = qSession.createTextMessage( sMsgText );
qSender.send( tm );
}
...
} // end sendMsg
public void onMessage( Message msg )
{
try
{
String sMessage = ((TextMessage) msg).getText();
...
}
...
} // end onMessage
...
// if the QueueConnection issued start() for incoming
// messages, invoke stop() prior to exit.
// close the QueueConnection before exiting!!! This
// operation will also close the Session and Sender.
} // end class XXX