Message-Driven Beans

A message-driven bean (MDB) is, by design, an asynchronous message consumer. The container invokes an MDB as the result of the arrival of a JMS message. An MDB has neither a home nor a remote interface, and consists of only the message bean class and a deployment descriptor. The bean class must implement both the MessageDrivenBean interface and the MessageListener interface. An MDB is container managed, and all configurable administered objects are specified declaratively in the deployment descriptor. A client accesses a message-driven bean through JMS by sending messages to the JMS Destination (Queue or Topic) for which the MDB class is the MessageListener. The client has no direct interaction with MDBs (see Figure 13.7).

Figure 13.7. The client view of a message-driven bean.


Note

Other EJB types, such as session and entity beans, are synchronous by design. When they issue an RMI call, they have to wait until they get back a reply. A message-driven bean is designed to handle asynchronous message calls.


Message-driven bean instances are stateless, have no conversational state, and are also anonymous, with no client-visible identity. This makes them an excellent candidate for instance pooling. An MDB is simply a more convenient component to develop a JMS consumer as part of an enterprise application.

The following is an example of an MDB. Note that the onMessage() method must be implemented for the MessageListener interface. Other methods are implemented for the MessageDrivenBean interface.

import javax.ejb.*;
import javax.jms.*;
public class RegistrarMDB implements MessageDrivenBean, MessageListener {
  protected MessageDrivenContext ctx;
  public void setMessageDrivenContext(MessageDrivenContext ctx) {
   this.ctx = ctx;
  }
  public void ejbCreate() {}
  public void ejbRemove() {}
  public void onMessage(Message message) {
    try {
       TextMessage msg = (TextMessage)message;
       System.err.println("Registrar received a new message: " +
                   msg.getText());
    } catch(JMSException e) {
     e.printStackTrace();
    }
  }
}

The setMessageDrivenContext() method is called by the EJB container to associate a message-driven bean instance with its context. Also, the onMessage() method is called by the container when a message has arrived for the bean to service. The onMessage method has one argument, which is the incoming message, and it contains the business logic that handles the processing of the message.

Day 14 will discuss message-driven beans in more detail.

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

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