ActiveMQ发布/订阅模式实例

1. 发送端

package com.ainy.demo;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.JMSException;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * 

* TODO 发布/订阅模式 发送 *

* * @author AINY * @version 2019年4月15日 */
public class SendActiveMqTopic { public static void main(String[] args) throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://10.2.7.7:61616"); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic("test-topic"); MessageProducer producer = session.createProducer(topic); TextMessage message = session.createTextMessage("消息内容ceshi"); producer.send(message); producer.close(); session.close(); connection.close(); } }

2. 接收

package com.ainy.demo;

import java.io.IOException;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * 

* TODO 发布/订阅模式 接收 *

* * @author AINY * @version 2019年4月15日 */
public class ReceiveActiveMqTopic { public static void main(String[] args) throws JMSException, IOException { // 1.创建连接工厂对象 ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://10.2.7.7:61616"); // 2.创建Connection对象 Connection connection = connectionFactory.createConnection(); // 3.开启连接 connection.start(); // 4.创建会话session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 5.topic主题 Topic topic = session.createTopic("test-topic"); // 6.创建消息的提供者consumer MessageConsumer consumer = session.createConsumer(topic); // 7.设置监听器 consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; try { System.out.println(textMessage.getText()); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); // 8.等待接收消息 System.out.println("topic消费者开始接收消息"); System.in.read(); // 9.close consumer.close(); session.close(); connection.close(); System.out.println("关闭..."); } }

3. 测试方法,将消费者运行两次,也就是两个消费者,然后运行发送者,会发现两个接收端全部收到了消息,也就是发布和订阅

你可能感兴趣的:(#,消息队列MQ)