导航页:https://blog.youkuaiyun.com/baokx/article/details/100745165
在非持久化模式下,生产者发送的消息在消费者接收到之前若mq宕机,则消费者无法再接收到消息。
在持久化模式下,生产者发送的消息在消费者接收到之前若mq宕机,在mq启动后消费者可以接收到消息,默认为此种模式。
持久topic之生产者
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @author kexiang.bao
* @create 2019-09-11 19:28
*/
public class JmsPersistTopicProducer {
private static final String ACTIVE_URL = "tcp://192.168.207.128:61616";
private static final String TOPIC_NAME = "persist_topic";
public static void main(String[] args) throws JMSException {
//1.创建连接工厂,采用默认的用户名和密码
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVE_URL);
//2.获取连接并启动访问
Connection connection = activeMQConnectionFactory.createConnection();
//3.创建session(参数:事务、签收)
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//4.创建目的地(具体是队列还是主题)
Topic topic = session.createTopic(TOPIC_NAME);
//5.创建消息的生产者
MessageProducer messageProducer = session.createProducer(topic);
//持久化属性
messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
//start下移
connection.start();
//6.使用messageProducer发送消息至队列
for (int i = 1; i <= 3; i++) {
//7.创建消息
TextMessage textMessage = session.createTextMessage("persist-topic-"+i);
System.out.println(textMessage.getText());
//8.发送消息
messageProducer.send(textMessage);
}
//9.关闭资源
messageProducer.close();
session.close();
connection.close();
System.out.println("持久化的topic发布成功");
}
}
持久topic之消费者
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.IOException;
/**
* @author kexiang.bao
* @create 2019-09-17 22:41
*/
public class JmsPersistTopicConsumer {
private static final String ACTIVE_URL = "tcp://192.168.207.128:61616";
private static final String TOPIC_NAME = "persist_topic";
public static void main(String[] args) throws JMSException, IOException {
System.out.println("我是持久topicClient1..");
//1.创建连接工厂,采用默认的用户名和密码
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVE_URL);
//2.获取连接并启动访问
Connection connection = activeMQConnectionFactory.createConnection();
connection.setClientID("c1");
//3.创建session(参数:事务、签收)
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//4.创建目的地(具体是队列还是主题)
Topic topic = session.createTopic(TOPIC_NAME);
TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic,"remark");
connection.start();
Message message = topicSubscriber.receive();
while(null != message){
TextMessage textMessage = (TextMessage) message;
System.out.println("接收到持久化的topic:"+textMessage.getText());
message = topicSubscriber.receive(5000L);
}
session.close();
connection.close();
}
}
先运行一次消费者,类似于注册
此时若运行生产者肯定可以接收到消息,不再做演示。将消费者停止运行:
然后运行生产者:
此时再次启动消费者: