Monday, June 29, 2009

Message Driven Bean

Message Driven Bean

Message Driven Bean (MDB) is an enterprise bean which runs inside the EJB container and it acts as Listener for the JMS asynchronous message . It does not have Home and Remote interface as Session or Entity bean. It is called by container when container receives JMS asynchronous message. MDB has to implement MessageListener which has a method onMessage(Message msg). When the container calls the MDB it passes the message to onMesage() method and then MDB process that message.

Example Program:

Server Side Program

package org.jboss.tutorial.mdb.bean;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.BytesMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination", propertyValue="queue/tutorial/example")
public class ExampleMDB implements MessageListener {
public void onMessage(Message recvMsg) {
System.out.println("Received message");
System.out.println("Received message object: " + recvMsg);
BytesMessage byteMsg = (BytesMessage) recvMsg;

Client Side Program
package org.jboss.tutorial.mdb.client;

import java.util.Properties;

import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

public class Client {
public static void main(String[] args) throws Exception {
QueueConnection cnn = null;
QueueSender sender = null;
QueueSession session = null;

Properties props = new Properties();
props.load(new FileInputStream("EJBJNDI.prop")); //
InitialContext ic = new InitialContext(props);

//InitialContext ctx = new InitialContext();
Queue queue = (Queue) ic.lookup("queue/tutorial/example");
QueueConnectionFactory factory = (QueueConnectionFactory) ic.lookup("ConnectionFactory");
cnn = factory.createQueueConnection();
session = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

TextMessage msg = session.createTextMessage("Hello World");

sender = session.createSender(queue);
System.out.println("Message sent successfully to remote queue.");



No comments:

Post a Comment