This article is more than 1 year old
Programming message services in Java
Asynchronous interactions seem to be the way of the future
The consumer
In our case, our consumer will be a Message Driven Bean (MDB). This is a type of Enterprise Java Bean (or EJB) that can be deployed within a J2EE application server such as JBoss. However, unlike other EJBs it only has an implementation class. In addition, the lifecycle of a MDB is also simpler than that of either session beans or entity beans. This is because all communication with a MDB is via a JMS queue or topic, no direct synchronous interaction is allowed.
With the advent of EJB3, the creation and definition of all EJBS and of MDBs in particular has become a lot simpler. It is only now necessary to implement the MessageListener
interface (a standard JMS interface) and to use some annotations to completely define your MDB. The MessageListener
interface defines a single method, namely the onMessage
method.
package com.regdeveloper.jms.mdb; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; @MessageDriven(name="NewsMessageDrivenBean", activationConfig = { @ActivationConfigProperty( propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty( propertyName="destination", propertyValue="queue/testQueue") }) public class NewsMDB implements MessageListener { public void onMessage(Message message) { try { String text = ((TextMessage)message).getText(); System.out.println("In the onMessage method(" + text + ")"); } catch (JMSException exp) { exp.printStackTrace(); } } }
The annotations on the class (the elements before the class definition starting with an “@” sign) are used to specify to the application server how to bind the message driven bean to an appropriate JMS queue. In this case, we give the MDB a name (“NewsMessageDrivenBean
”) and a configuration to be used during deployment. This configuration indicates that the MDB should be bound to a queue and that the queue to bind it to has a JNDI name of “queue/testQueue”.
The MDB is packaged up in a jar file (news.jar) and placed within an EAR file using the following application.xml file:
<?xml version="1.0" encoding="UTF-8" ?> <application xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application_1_4.xsd" version="1.4"> <display-name>News MDB App</display-name> <module> <ejb>news.jar</ejb> </module> </application>