ActiveMQ(九)--持久的Topic消息示例

本文介绍了如何在ActiveMQ中实现持久化的Topic消息。通过示例展示生产者发送消息及消费者接收消息的过程。即使消费者停止,再次启动后仍能接收到之前的消息,因为可能存在其他订阅者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生产者

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class PersistenceSender {
    public static void main(String[] args) throws JMSException, InterruptedException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.25.128:61616");
        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic("MyTopic2");
        MessageProducer producer = session.createProducer(destination);

        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        connection.start();

        for (int i = 0; i < 3; i++) {
            TextMessage message = session.createTextMessage("message--" + i);
            producer.send(message);
        }

        session.commit();
        session.close();
        connection.close();
    }
}

消费者

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class PersistenceReceiver {
    public static void main(String[] args) throws JMSException {
        //1:需要在连接上设置笑着id,用来识别消费者
        //2.需要创建TopicSubscriber来订阅
        //3.要设置好了过后再start这个connection
        //4.一定要先运行一次,等于向消息服务中间件注册这个消费者,然后在运行客户端发送消息,
        // 这个时候,无论消费者是否在线,都会接收到,不在线的话,下次连接的时候,会把没有收过的消息都接收下来。
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.25.128:61616");
        Connection connection = connectionFactory.createConnection();
        connection.setClientID("cc1");
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Topic destination = session.createTopic("MyTopic2");
        TopicSubscriber ts = session.createDurableSubscriber(destination, "T1");
        connection.start();
        Message message = ts.receive();//receive()是阻塞方法
        while (message != null) {
            TextMessage txtMsg = (TextMessage) message;
            System.out.println("收到消息:" + txtMsg.getText());
            message = ts.receive(1000L);
        }
        session.commit();
        session.close();
        connection.close();
    }
}

先运行消费者,然后停止消费者。看ActiveMQ的状态:

运行生产者:

再运行消费者:

说明,消费者消费消息之后,topic的Messages Dequeued还是0,这是因为,有可能有其他的消费者还订阅了。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值