Sending messages to a message topic

The following example illustrates how to send messages to a message topic:

package net.ensode.javaee8book.jmspubsubproducer; 
 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.annotation.Resource; 
import javax.enterprise.context.RequestScoped; 
import javax.inject.Named; 
import javax.jms.ConnectionFactory; 
import javax.jms.JMSContext; 
import javax.jms.JMSProducer; 
import javax.jms.Topic; 
 
@Named 
@RequestScoped 
public class MessageSender { 
 
    @Resource 
    private ConnectionFactory connectionFactory; 
    @Resource(mappedName = "jms/JavaEE8BookTopic") 
    private Topic topic; 
    private static final Logger LOG = 
        Logger.getLogger(MessageSender.class.getName()); 
 
    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!"; 
 
        LOG.log(Level.INFO, "Sending the following message: {0}", 
msg1); jmsProducer.send(topic, msg1); LOG.log(Level.INFO, "Sending the following message: {0}",
msg2); jmsProducer.send(topic, msg2); LOG.log(Level.INFO, "Sending the following message: {0}",
msg3); jmsProducer.send(topic, msg3); } }

As we can see, the preceding code is nearly identical to the MessageSender class we saw when we discussed Point-To-Point messaging. As a matter of fact, the only lines of code that are different are the ones that are highlighted. The JMS API was designed this way so that application developers do not have to learn two different APIs for the PTP and pub/sub domains.

Since the code is nearly identical to the corresponding example in the Message queues section, we will only explain the differences between the two examples. In this example, instead of declaring an instance of a class implementing javax.jms.Queue, we declare an instance of a class implementing javax.jms.Topic. We then pass this instance of javax.jms.Topic as the first method of the send() method of our JMSProducer object, along with the message we wish to send.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.137.38