J2EE Messaging
877
Publisher
Topic
Subscriber
Subscriber
Subscriber
Publish a
message
Receive
message
published
to topic
A JMS Publisher
This is a short example of a JMS client that reads user input and publishes the message to the MyJMSTopic
topic (stored in the utility class WeblogicJMSDetails) until the user inputs q or Q. The following code is
from Publisher.java, which you can download from the Wrox web site (http//www.wrox.com):
package pubsub;
import common.*;
import java.io.*;
import javax.jms.*;
import javax.naming.*;
public class Publisher
{
protected TopicConnectionFactory connectionFactory;
protected TopicConnection topicConnection;
protected TopicSession topicSession;
protected TopicPublisher topicPublisher;
protected Topic topic;
protected TextMessage message;
public Publisher() throws NamingException, JMSException
{
The context is the client's connection to JNDI. Note that the WeblogicJMSDetails class will be
described later:
// Obtain an initial context - JMS Vendor Specific
InitialContext ctx = WeblogicJMSDetails.getInitialContext();
Once the constructor has an initial context, it looks up a topic connection factory using JNDI, it uses the
connection factory to create a connection, which is the client's access to the messaging system and
performs resource allocation and management.
The JMS_CONNECTION_FACTORY constant in the code specifies the JNDI name of the connection factory:
connectionFactory = (TopicConnectionFactory)
ctx.lookup(WeblogicJMSDetails.JMS_CONNECTION_FACTORY);