Pages

2014-08-15

Java EE: Sending messages to a message topic/Receiving messages from a message topic

Sending messages to a JMS topic is very similar to sending messages to a queue; simply inject the required resources and make some simple JMS API calls. The following example illustrates how to send messages to a message topic:

import javax.annotation.Resource;
import javax.jms.ConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.JMSProducer;
import javax.jms.Topic;

public class MessageSender {

@Resource(mappedName = "jms/GlassFishBookConnectionFactory")
private static ConnectionFactory connectionFactory;
@Resource(mappedName = "jms/GlassFishBookTopic")
private static Topic topic;

public void produceMessages() {
   JMSContext jmsContext = connectionFactory.createContext();
   JMSProducer jmsProducer = jmsContext.createProducer();
   String msg1 = "Testing, 1, 2, 3. Can you hear me?";
   String msg2 = "Do you copy?";
   String msg3 = "Good bye!";
   System.out.println("Sending the following message: " + msg1);
   jmsProducer.send(topic, msg1);
   System.out.println("Sending the following message: " + msg2);
   jmsProducer.send(topic, msg2);
   System.out.println("Sending the following message: " + msg3);
   jmsProducer.send(topic, msg3);
}

Just as sending messages to a message topic is nearly identical to sending messages  receiving messages from a message topic is nearly identical to receiving messages from a message queue, as can be seen in the following example:


import javax.annotation.Resource;

import javax.jms.ConnectionFactory;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.Topic;

public class MessageReceiver {
@Resource(mappedName = "jms/GlassFishBookConnectionFactory")
private static ConnectionFactory connectionFactory;
@Resource(mappedName = "jms/GlassFishBookTopic")
private static Topic topic;
public void getMessages() {
   String message;
   boolean goodByeReceived = false;
   JMSContext jmsContext = connectionFactory.createContext();
   JMSConsumer jMSConsumer = jmsContext.createConsumer(topic);
   System.out.println("Waiting for messages...");
   while (!goodByeReceived) {
        message = jMSConsumer.receiveBody(String.class);
        if (message != null) {
           System.out.print("Received the following message: ");
           System.out.println(message);
           System.out.println();
           if (message.equals("Good bye!")) {
                    goodByeReceived = true;
           }
        }
    }
}

No comments:

Post a Comment