先消费者、后生产者:消费者只能消费它注册之后生产者生产的消息
消费者: 可以多个
**
* @author AW
* @date 2019/11/20 11:57
* @desc topic模式消费者
*/
public class MyMessageTopicConsumer2 {
/** 定义ActivMQ的连接地址 8161是后台管理系统(url中访问后台管理页用此端口),61616是给java用的tcp端口*/
private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
/** 定义发送消息的队列名称 8161是后台管理系统(url中访问后台管理页用此端口),61616是给java用的tcp端口*/
private static final String TOPIC_NAME = "MyTopicMessage";
public static void main(String[] args) throws JMSException {
//创建连接工厂
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
//创建连接
Connection connection = activeMQConnectionFactory.createConnection();
//打开连接
connection.start();
//创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//创建队列目标
Destination destination = session.createTopic(TOPIC_NAME);
//创建消费者
MessageConsumer consumer = session.createConsumer(destination);
//创建消费的监听
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("获取消息:" + textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
}
}
topic模式:生产者
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @author AW
* @date 2019/11/20 11:54
* @desc topic 消息生产者
*/
public class MyMessageTopicProducer {
/**
* 定义ActivMQ的连接地址 8161是后台管理系统(url中访问后台管理页用此端口),61616是给java用的tcp端口
*/
private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
/** 定义发送消息的主题名称 */
private static final String TOPIC_NAME = "MyTopicMessage";
public static void main(String[] args) throws JMSException {
//创建连接工厂
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
//创建连接
Connection connection = activeMQConnectionFactory.createConnection();
//打开连接
connection.start();
//创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//创建队列目标
Destination destination = session.createTopic(TOPIC_NAME);
//创建一个生产者
javax.jms.MessageProducer producer = session.createProducer(destination);
//创建模拟100个消息
for (int i = 1; i <= 100; i++) {
TextMessage message = session.createTextMessage("当前message是(主题模型):" + i);
//发送消息
producer.send(message);
//在本地打印消息
System.out.println("我现在发的消息是:" + message.getText());
}
//关闭连接
connection.close();
}
}
消费后