概述
JMS的topic模式生活中也很常见,比如我们订阅一个公众号,就会有消息推送给我们;
但是在我们订阅公众号的这个时间点之前的消息,我们是收不到的
所以我们的案例,是从消费者开始写的,只有当消费者存在的情况,生产者发送的消息才会有人接收,否则就是与空气斗智斗勇。
pom依赖
<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.14.3</version>
</dependency>
</dependencies>
消费者代码
与之前的案例一样,
connectionFactory生成connection
connection创建session
session创建消费者和主题,
消费者是通过主题与生产者联系起来的,这里的topic是test2,也就是消费者关注的test2这个主题,当有生产者向这test2发送消息时,只要消费者还在运行,就会收到这个消息;
demo里我们接受10条消息
package com.demo.topic01;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* Created by Administrator on 2019/9/29 0029.
*/
public class TopicConsumer {
public static void main(String[] args) throws JMSException {
System.out.println("我是消费者1");
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("test2");
MessageConsumer consumer = session.createConsumer(topic);
for (int i = 0; i < 10; i++) {
Message message = consumer.receive();
if (message instanceof TextMessage) {
TextMessage text = (TextMessage) message;
System.out.println(text.getText());
}
}
consumer.close();
session.close();
connection.close();
}
}
此时进入控制界面,可以看到topic下面已经有1个消费者了,运行2次代码就会有两个消费者
生产者代码
connectionFactory生成connection
connection创建session
session创建生产者和主题
package com.demo.topic01;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* Created by Administrator on 2019/9/29 0029.
*/
public class TopicProduce {
public static void main(String[] args) throws JMSException {
System.out.println("我是生产者");
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("test2");
MessageProducer producer = session.createProducer(topic);
TextMessage message = session.createTextMessage();
message.setText("你订阅了我,发个消息证明一下" + System.currentTimeMillis());
producer.send(message);
producer.close();
session.close();
connection.close();
}
}
在控制界面中可以看到,test2有2个消费者,我启动了2次生产者,所以有了如下数据
2个消费者*2条消息=4,所以消息出队是4