Writing a Simple Message-Driven Bean

As you work through this section, you will create a Message-driven bean that that simply prints out the contents of a text message on screen.

So that the Message-driven bean can work asynchronously you will employ the MessageListener interface. This interface and the associated onMessage() method, which is invoked each time a message is available at the destination, were fully described in Day 9.

Implementing the Interfaces

As already stated, all Message-driven beans must implement the MessageDrivenBean and MessageListener interfaces.

import javax.ejb.*;
import javax.jms.*;
public class MDBPrintMessage implements MessageDrivenBean, MessageListener {
// class body not shown – see listing 10.1
}

Just like the EntityBean and SessionBean interfaces, the MessageDrivenBean interface extends the javax.ejb.EnterpriseBean interface.

The MessageDrivenBean interface contains only two methods—setMessageDrivenContext() and ejbRemove(), see the class diagram in Figure 10.4.

Figure 10.4. The MessageDrivenBean class diagram.


You also need to supply an ejbCreate() method.

In this example, we have no need to create or store resources, and it is so simple that we will leave all the required methods blank.

public void setMessageDrivenContext (MessageDrivenContext ctx) {}
public void ejbRemove() {}
public void ejbCreate() {}

The MessageListener interface is where the Message-driven bean carries out the bean's business logic. As already stated, it consists of the single method onMessage(). In this example, we will simply test that the message is a TextMessage and, if it is, print it to the screen. The full code is shown in Listing 10.1.

Listing 10.1. Simple Print Message Message-Driven Bean
1: import javax.ejb.*;
 2: import javax.jms.*;
 3:
 4: public class MDBPrintMessage implements MessageDrivenBean, MessageListener {
 5:
 6:     public void setMessageDrivenContext (MessageDrivenContext ctx) {}
 7:     public void ejbRemove() {}
 8:     public void ejbCreate() {}
 9:
10:     public void onMessage(Message message) {
11:         try {
12:             if (message instanceof TextMessage)
13:             {
14:                  String text = ((TextMessage) message).getText();
15:                  System.out.println("Received: " + text);
16:             }
17:         } catch(Exception ex) {
18:             throw new EJBException(ex);
19:         }
20:     }
21: }

As you can see, there is no reference in this code to any particular JMS queue or topic. This means that the bean is not only generic and can be associated with any queue or topic at deployment time, it can also be associated with several different queues or topics at the same time.

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

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