EJB---->消息驱动bean--Topic 消息的发送与接收(Pub/sub 消息传递模型)
TopicSender.java (Topic 消息发送者)
import javax.annotation.Resource; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import com.foshanshop.ejb3.TSender; /** * 发送Topic消息 * @author lihuoming * */ @Stateless @Remote (TSender.class) public class TSenderBean implements TSender { @Resource(mappedName="TopicConnectionFactory") private TopicConnectionFactory factory; @Resource(mappedName="topic/chatTopic") private Topic destination; public void send(String msg) { TopicConnection conn = null; TopicSession session = null; try { conn = factory.createTopicConnection(); session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); TextMessage text = session.createTextMessage(msg); producer.send(text); }catch (Exception e){ e.printStackTrace(); }finally{ try { session.close (); conn.close(); } catch (JMSException e) { e.printStackTrace(); } } } }TopicPrintBeanOne.java(Topic 消息接收者之一)
package com.foshanshop.ejb3.impl; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Topic"), @ActivationConfigProperty(propertyName="destination", propertyValue="topic/chatTopic") }) public class TopicPrintBeanOne implements MessageListener{ public void onMessage(Message msg) { try { TextMessage tmsg = (TextMessage) msg; String content = tmsg.getText(); System.out.println(this.getClass().getName()+"=="+ content); } catch (Exception e){ e.printStackTrace(); } } }
TopicPrintBeanTwo.java(Topic 消息接收者之二)
package com.foshanshop.ejb3.impl; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Topic"), @ActivationConfigProperty(propertyName="destination", propertyValue="topic/chatTopic") }) public class TopicPrintBeanTwo implements MessageListener{ public void onMessage(Message msg) { try { TextMessage tmsg = (TextMessage) msg; String content = tmsg.getText(); System.out.println(this.getClass().getName()+"=="+ content); } catch (Exception e){ e.printStackTrace(); } } }