Message-driven beans

The purpose of a message-driven bean is to consume messages from a Java Message Service (JMS) queue or a JMS topic, depending on the messaging domain used (refer to Chapter 8, Java Message Service). A message-driven bean must be decorated with the @MessageDriven annotation; the mappedName attribute of this annotation must contain the Java Naming and Directory Interface (JNDI) name of the JMS message queue or JMS message topic that the bean will be consuming messages from. The following example illustrates a simple message-driven bean:

package net.ensode.javaeebook; 
 
import javax.ejb.MessageDriven; 
import javax.jms.JMSException; 
import javax.jms.Message; 
import javax.jms.MessageListener; 
import javax.jms.TextMessage; 
 
@MessageDriven(mappedName = "jms/JavaEE8BookQueue") 
public class ExampleMessageDrivenBean implements MessageListener 
{ 
  public void onMessage(Message message) 
  { 
    TextMessage textMessage = (TextMessage) message; 
    try 
    { 
      System.out.print("Received the following message: "); 
      System.out.println(textMessage.getText()); 
      System.out.println(); 
    } 
    catch (JMSException e) 
    { 
      e.printStackTrace(); 
    } 
  } 
} 

Message-driven beans must be decorated with the @MessageDriven annotation. They listen for messages on the queue or topic defined in the mappedName attribute of the @MessageDriven interface (jms/JavaEEBookQueue in this example).

It is recommended, but not required, for message-driven beans to implement the javax.jms.MessageListener interface; however message-driven beans must have a method called onMessage() whose signature is identical to the preceding example.

Client applications never invoke a message-driven bean's methods directly; instead they put messages in the message queue or topic, then the bean consumes those messages and acts appropriately. The preceding example simply prints the message to standard output; since message-driven beans execute inside an EJB container, standard output gets redirected to a log. If using GlassFish, the server log file can be found at [GlassFish installation directory]/glassfish/domains/domain1/logs/server.log.

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

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