论坛首页 入门技术论坛

jms2 pub2sub模式

浏览 1178 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-03-04  

服务端定义了两个消费者

 

@MessageDriven(activationConfig={
		@ActivationConfigProperty(propertyName="destinationType",propertyValue="javax.jms.Topic"),
		@ActivationConfigProperty(propertyName="destination",propertyValue="topic/myTopic")
}
)
public class TopicMessageBean01 implements MessageListener {

	public void onMessage(Message msg) {
		TextMessage txtMsg=(TextMessage)msg;
		String s="";
		try {
			s = txtMsg.getText();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("TopicMessageBean01接收消息:"+s);

	}

}

 

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(activationConfig={
		@ActivationConfigProperty(propertyName="destinationType",propertyValue="javax.jms.Topic"),
		@ActivationConfigProperty(propertyName="destination",propertyValue="topic/myTopic")
}
)
public class TopicMessageBean02 implements MessageListener {

	public void onMessage(Message msg) {
		TextMessage txtMsg=(TextMessage)msg;
		String s="";
		try {
			s = txtMsg.getText();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("TopicMessageBean02接收消息:"+s);

	}

}

 

 

 

 

客户端的发布者代码

 

import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.InitialContext;

public class Test {
	public static void main(String[] args) throws Exception {
		InitialContext context=new InitialContext();
		//获得QueueConnectionFactory
		TopicConnectionFactory factory =(TopicConnectionFactory)context.lookup("TopicConnectionFactory");
		//创建QueueConnection
		TopicConnection conn=factory.createTopicConnection();
		//创建会话
		//p1:与事务有关 true:表示最后提交  false:表示自动提交
		//p2:表示接收方向消息中间件发送确认通知,我们这里采用自动通知类型
		TopicSession session=conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
		//取得destination
		Topic topic=(Topic)context.lookup("topic/myTopic");
		//消息生产者
		MessageProducer publisher=session.createProducer(topic);
		
		//定义消息
		Message msg=session.createTextMessage("消息来了");
		//发送消息
		publisher.send(topic, msg);
		
		session.close();
		conn.close();
	}
}

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics