JMS订阅的发布和接收

字体大小: 中小 标准 ->行高大小: 标准
1.jms消息订阅的发送

		// 创建连接
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
		Connection connection = factory.createConnection();
		connection.start();

		// 创建一个Topic
		Topic topic = new ActiveMQTopic("testTopic");
		Session session = connection.createSession(false,
				Session.AUTO_ACKNOWLEDGE);

		MessageProducer publisher = session.createProducer(topic);
		// 定义消息
		Message msg = session.createTextMessage("消息来了");
		// 发送消息
		publisher.send(topic, msg);

		// 关闭连接
		publisher.close();
		session.close();
		connection.close();

2.jms消息订阅的接收
  //创建连接
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
Connection connection = factory.createConnection();
connection.setClientID("client-name");
connection.start();

// 创建一个Topic
Topic topic = new ActiveMQTopic("testTopic");
Session session = connection.createSession(false,
				Session.AUTO_ACKNOWLEDGE);
MessageConsumer comsumer1 = session.createDurableSubscriber(topic,
				"my-sub-name");

// 注册消费者1,接收消息
		while (true) {
			TextMessage message = (TextMessage) comsumer1.receive(1000);
			if (null != message)
				System.out.println("收到消息:" + message.getText());
			else
				break;
		}

//关闭连接
session.close();
connection.close();

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/68497.html