J2EE Messaging
881
// Obtain an initial context - JMS Vendor Specific
InitialContext ctx = WeblogicJMSDetails.getInitialContext();
// Look up a connection factory
connectionFactory = (TopicConnectionFactory)
ctx.lookup(WeblogicJMSDetails.JMS_CONNECTION_FACTORY);
// Create a connection
topicConnection = connectionFactory.createTopicConnection();
// Create a session
topicSession = topicConnection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
// Look up the topic
topic = (Topic) ctx.lookup(WeblogicJMSDetails.TOPIC_NAME);
The Subscriber creates a topic subscriber to listen on the topic. The topic session's
createSubscriber(Topic topic) method creates a subscriber on the specified topic
MyJMSTopic in this case.
There are two types of subscriptions to a topic: durable and non-durable. If a client has a durable
subscription to a topic it receives messages that are sent even when the client is not online. The session
holds on to the messages until they expire or until the session receives a confirmation of message receipt
from the client with a durable subscription.
A durable subscription involves more overhead than a non-durable subscription, so the developer must
decide whether or not it is worth compromising server performance for the client to receive messages
that are sent while the client is disconnected from the server. A client can create a durable subscription
by calling createDurableSubscriber(Topic topic):
// Create a Subscriber for the topic
topicSubscriber = topicSession.createSubscriber(topic);
In addition to creating a topic subscriber, a client must set a message listener on the topic before it can
receive messages. The setMessageListener(MessageListener messageListener) method sets
a message listener on the subscriber's topic. In this example, the message listener is the Subscriber
class itself. The message listener must implement the MessageListener interface and must also
provide a method for retrieving messages:
// Set ourselves as the listener for the messages
topicSubscriber.setMessageListener(this);
// Start up the connection so we can get messages.
topicConnection.start();
}
/**
* Closes JMS connection objects.
*/
public void close() throws JMSException
{
topicSubscriber.close();
topicSession.close();
topicConnection.close();
}