ActiveMQ Topic消息持久化订阅

一、持久化到文件(默认)

第一步:在${activemq.base}/conf/activemq.xml文件中配置持久化适配器

ActiveMQ Topic消息持久化订阅_第1张图片

第二步:在java代码中发送消息时

ActiveMQ Topic消息持久化订阅_第2张图片

第三步:消息订阅方创建消费对象时

代码示例:

public class TopicPersistentTest {
    //编写消息的发送方---消息的生产者
    @Test
    public void test1() throws Exception {
        //创建连接工厂对象
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        //从工厂中获取连接对象
        Connection connection = connectionFactory.createConnection();
        //连接MQ服务
        connection.start();
        //获得回话(session)对象
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //通过session对象创建Topic
        Topic topic = session.createTopic("itheimaTopic");
        //通过session对象创建消息的发送者
        MessageProducer producer = session.createProducer(topic);
        //通过session创建消息对象
        TextMessage message = session.createTextMessage("ping111");
        //发送消息
        producer.send(message,DeliveryMode.PERSISTENT,1,1000*60*60*24);
        //关闭相关资源
        producer.close();
        session.close();
        connection.close();
    }

    //编写消息的接收方---消息的消费者
    @Test
    public void test2() throws Exception {
        //创建连接工厂对象
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        //从工厂中获取连接对象
        Connection connection = connectionFactory.createConnection();
        //设置客户端id
        connection.setClientID("client-1");
        //连接MQ服务
        connection.start();
        //获得回话(session)对象
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //通过session对象创建Topic
        Topic topic = session.createTopic("itheimaTopic");
        //通过session对象创建消息的消费者
        //MessageConsumer consumer = session.createConsumer(topic);
        //客户端持久化订阅
        TopicSubscriber consumer = session.createDurableSubscriber(topic, "client1");
        //指定消息监听器
        consumer.setMessageListener(new MessageListener() {
            //当我们监听的topic 中存在消息 这个方法自动执行
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println("消费者接收到了消息:" + textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        //消息消费者 要时刻在线 连接对象 会话对象均不需要关闭
        //模拟web场景当执行结束后不能让线程结束
        while (true) {
            //死循环  不让消费者线程停掉
        }
    }
}

二、持久化到数据库(mysql)

第一步:将mysql数据库驱动复制到activeMQ的lib目录下

 ActiveMQ Topic消息持久化订阅_第3张图片

第二步:在${activemq.base}/conf/activemq.xml文件中配置持久化适配器

 
			
        

第三步:在${activemq.base}/conf/activemq.xml文件中配置数据源


	     
		 
		 
		 
		 
	

代码同上代码示例相同

执行结果刷新active数据库生成了三张表

ActiveMQ Topic消息持久化订阅_第4张图片

其中activmq_msgs表中的数据就是我们持久化到数据库中的消息:

ActiveMQ Topic消息持久化订阅_第5张图片

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