ActiveMQ(四)——ActiviteMQ实现方式之三:主题发布/订阅

消息发送方代码:

 

package com.mycom.activemq;

import java.util.HashMap;
import java.util.Map;

import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * ActiviteMQ方式3:主题发布/订阅方式
 * 消息发送方(生产者)
 * 
 * @author guweiqiang
 */
public class TopicSender {

	/**
	 * 发送消息
	 */
	public static void sendMessage(String brokerUrl, Map<String, Object> map) {
		// TopicConnectionFatory : 连接工厂
		TopicConnectionFactory topicConnectionFactory;
		
		// TopicConnection : JMS客户端到JMS Provider的连接
		TopicConnection topicConnection = null;
		
		// TopicSession : 发送/接收消息的会话
		TopicSession topicSession = null;
		
		// Topic : 发布/订阅队列
		Topic topic;
		
		// TopicPublisher : 消息发布者
		TopicPublisher publisher;
		
		try{
			// 创建连接工厂TopicConnectionFactory实例
			topicConnectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, brokerUrl);
			
			// 创建连接 TopicConnection
			topicConnection = topicConnectionFactory.createTopicConnection();
			
			// 启动连接
			topicConnection.start();
			
			// 创建会话 TopicSession
			topicSession = topicConnection.createTopicSession(Boolean.TRUE, TopicSession.AUTO_ACKNOWLEDGE);
			
			// 创建发布/订阅队列 Topic
			topic = topicSession.createTopic("ThirdQueue");
			
			// 创建消息发布者 TopicPublisher
			publisher = topicSession.createPublisher(topic);
			publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // 设置持久化模式
			
			// 准备工作已完成,可以开始发送消息了
			// 发送消息
			MapMessage mapMsg = topicSession.createMapMessage();
			mapMsg.setString("NAME", (String) map.get("name"));
			mapMsg.setString("LANGUAGE", (String) map.get("language"));
			System.out.println(mapMsg);
			publisher.send(mapMsg);
			
			// 提交会话
			topicSession.commit();
			
		} catch(Exception ex){
			ex.printStackTrace();
		} finally {
			// 释放资源
			if(topicSession != null){
				try {
					topicSession.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if(topicConnection != null){
				try {
					topicConnection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 测试
	 */
	public static void main(String[] args) {
		String brokerUrl = "tcp://127.0.0.1:61616";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", "guweiqiang3");
		map.put("language", "java");
		TopicSender.sendMessage(brokerUrl, map);
	}
}

 

 

消息接收方代码:

 

package com.mycom.activemq;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * ActiviteMQ方式3:主题发布/订阅方式 
 * 消息接收方(消费者)
 * 
 * @author guweiqiang
 */
public class TopicReceiver {

	/**
	 * 接收消息
	 */
	public static void receiveMessage(String brokerUrl) {
		// TopicConnectionFatory : 连接工厂
		TopicConnectionFactory topicConnectionFactory;

		// TopicConnection : JMS客户端到JMS Provider的连接
		TopicConnection topicConnection = null;

		// TopicSession : 发送/接收消息的会话
		TopicSession topicSession = null;

		// Topic : 发布/订阅队列
		Topic topic;

		// TopicSubscriber : 消息订阅者
		TopicSubscriber topicSubscriber;

		try {
			// 创建连接工厂TopicConnectionFactory实例
			topicConnectionFactory = new ActiveMQConnectionFactory(
					ActiveMQConnection.DEFAULT_USER,
					ActiveMQConnection.DEFAULT_PASSWORD, brokerUrl);

			// 创建连接 TopicConnection
			topicConnection = topicConnectionFactory.createTopicConnection();

			// 启动连接
			topicConnection.start();

			// 创建会话 TopicSession
			topicSession = topicConnection.createTopicSession(Boolean.TRUE,
					TopicSession.AUTO_ACKNOWLEDGE);

			// 创建发布/订阅队列 Topic
			topic = topicSession.createTopic("ThirdQueue");

			// 创建消息订阅者 TopicSubscriber
			topicSubscriber = topicSession.createSubscriber(topic);

			// 准备工作已经完成,可以开始接收消息了(通过实现MessageListener的onMessage方法来接收消息)
			topicSubscriber.setMessageListener(new MessageListener() {

				@Override
				public void onMessage(Message message) {
					if (message != null) {
						MapMessage mapMsg = (MapMessage) message;
						try {
							System.out.println("NAME:"
									+ mapMsg.getString("NAME") + "\t LANGUAGE:"
									+ mapMsg.getString("LANGUAGE"));
						} catch (JMSException e) {
							e.printStackTrace();
						}
					}
				}
			});

			Thread.sleep(1000 * 100); // 进程睡眠一段时间再关闭
			
			// 提交会话
			topicSession.commit();

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			// 释放资源
			if (topicSession != null) {
				try {
					topicSession.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if (topicConnection != null) {
				try {
					topicConnection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 测试
	 */
	public static void main(String[] args) {
		String brokerUrl = "tcp://127.0.0.1:61616";
		TopicReceiver.receiveMessage(brokerUrl);
	}

}

 

 

启动ActiveMQ,再在本地执行上述发送方和接收方代码,运行结果如下:

发送方console:

 

ActiveMQMapMessage {commandId = 0, responseRequired = false, messageId = null, originalDestination = null, originalTransactionId = null, producerId = null, destination = null, transactionId = null, expiration = 0, timestamp = 0, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = false, type = null, priority = 0, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = false, readOnlyBody = false, droppable = false} ActiveMQMapMessage{ theTable = {NAME=guweiqiang3, LANGUAGE=java} }

 

 

接收方console:

NAME:guweiqiang3	 LANGUAGE:java

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值