本文主要是介绍EJB——消息驱动Bean,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
驱动Bean (MDB)提供了一个实现异步通信比直接使用Java消息服务(JMS)更容易地方法。创建MDB接收异步JMS消息。容器处理为JMS队列和主题所要求加载处理的大部分工作。它向相关的MDB发送所有的消息。一个MDB允许J2EE应用发送异步消息,该应用能处理这些消息。实现javax.jms.MessageListener接口和使用@MessageDriven注释该Bean来指定一个Bean是消息驱动Bean。
import javax.ejb.MessageDriven;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.Inject;
import javax.jms.*;
import java.util.*;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.ejb.TimerService;
@MessageDriven(
activationConfig = {
@ActivationConfigProperty(propertyName="connectionFactoryJndiName", propertyValue="jms/TopicConnectionFactory"),
@ActivationConfigProperty(propertyName="destinationName", propertyValue="jms/myTopic"),
@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Topic"),
@ActivationConfigProperty(propertyName="messageSelector", propertyValue="RECIPIENT = 'MDB'")
}
)/**
*监听可配置JMS队列或者主题和通过当一个消息发送到队列或者主题
*调用它的onMessage()方法得到提醒的一个简单的消息驱动
*该Bean打印消息的内容
*/public class MessageLogger implements MessageListener, TimedObject
{@Inject javax.ejb.MessageDrivenContext mc;public void onMessage(Message message)
{
System.out.println("onMessage() - " + message);
try
{String subject = message.getStringProperty("subject");String inmessage = message.getStringProperty("message");System.out.println("Message received\n\tDate: " + new java.util.Date() + "\n\tSubject: " + subject + "\n\tMessage: " + inmessage + "\n");System.out.println("Creating Timer a single event timer");TimerService ts = mc.getTimerService();Timer timer = ts.createTimer(30000, subject);System.out.println("Timer created by MDB at: " + new Date(System.currentTimeMillis()) +" with info: "+subject);}catch (Throwable ex){ex.printStackTrace();}
}public void ejbTimeout(Timer timer)
{System.out.println("EJB 3.0: Timer with MDB");System.out.println("ejbTimeout() called at: " + new Date(System.currentTimeMillis()));return;
}
}
这篇关于EJB——消息驱动Bean的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!