EJB——消息驱动Bean

来源:互联网 发布:淘宝美工在哪里学 编辑:程序博客网 时间:2024/04/27 15:29

         驱动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;}}


0 0
原创粉丝点击