Coding JMS Publishers and Subscribers
After you have defined your topics and subscriptions through the MQ Explorer, writing publisher and subscriber applications is easy. To publish a message, you must write a message to a topic (just as you would with a queue). Subscribers simply read messages from queues.
The downloadable source code for this article uses generic JMS interfaces, which treat queues and topics uniformly as destinations. It provides compiled classes that include a News publisher and two subscribers (corresponding to the Email and SMS applications).
The following are brief explanations of the classes.
This class includes methods to retrieve objects by name through JNDI lookup (see Listing 1
). You will use methods in this class to retrieve references to the JMS objects you have already defined.
This class publishes messages to the News topic (see Listing 2
). The starting point is a connection factory lookup. You use the factory to create a connection:
connection = factory.createConnection();
You use the connection object to create a session:
session = connection.createSession( transacted, Session.AUTO_ACKNOWLEDGE);
To publish messages, retrieve a News destination object, create a MessageProducer, and then send messages:
destination = jndiUtil.getDestination("NewsTopic");
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage("No News is Good News!");
EmailSubscriber and SMSSubscriber
These two classes represent the email application and the SMS application (see Listing 3
and Listing 4
). Because you already defined subscriptions in MQ Explorer, the two applications simply read messages from the subscriber queues.
The code is similar to the NewsPublisher class, except that it uses a MessageConsumer to retrieve messages from queues:
consumer = session.createConsumer(destination);
TextMessage iMsg = (TextMessage) consumer.receive(1000);
Compiling and Running the Sample Classes
The JAR files required to compile and run the sample classes are automatically added to the CLASSPATH environment variable when you install WMQ. The required JARs are located in C:\Program Files\IBM\WebSphere MQ\Java\lib
, including the JARs you need for JMS and JNDI. You just need to add the sample classes from the code download to your CLASSPATH environment variable.
To publish messages, run the NewsPublisher:
Run both subscribers after your run the NewsPublisher to retrieve messages. Each class should retrieve its own copy of the messages published by NewsPublisher:
You're done. Your sample classes should compile and run successfully.
So the next time you're designing messaging-based applications, don't be so quick to dismiss publish/subscribe. Remember this article and how quickly you were able to get started with publish/subscribe messaging.