ActiveMQ的消息消费者事物小Demo

在消费中当createSession()方法是true
需要提交事物session.commit();,这样才不会造成重复消费的情况

如图
ActiveMQ事物消费者.png

消息消费者代码

/**
 * @author songzixian
 * @description ActiveMQ消费者
 */
public class JmsConsumer {

    public static final String ActiveMQ_URL="tcp://192.168.78.138:61616";
    public static final String QUEUE_NAME = "queue01";

      @Test
      public void test01() throws Exception{
        System.out.println("我是1号消费者");

        //1.创建连接工厂,按照指定的url地址,采用默认帐号密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ActiveMQ_URL);

        //2.通过连接工厂,获得连接connection
        Connection connection = activeMQConnectionFactory.createConnection();
        //启动
        connection.start();
        //3.创建会话session
        Session session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);

        //4.创建目的地(具体是列队还是主题topic);
        Queue queue = session.createQueue(QUEUE_NAME);


        //5.创建消息消费者
        MessageConsumer messageConsumer = session.createConsumer(queue);

        while (true){
            TextMessage textMessage = (TextMessage) messageConsumer.receive(4000L);
            if (textMessage != null){
                System.out.println("消费者接收到了消息msg"+textMessage.getText());
            }else {
                break;
            }
        }
        
        //关闭资源
        messageConsumer.close();
        //提交事物(告诉mq已消费过,不会重复消费)
        session.commit();
        session.close();
        connection.close();
    }

配合消息生产者一起使用:ActiveMQ的消息生成者事物介绍说明

Last modification:July 19th, 2019 at 06:31 am
如果觉得这篇技术文章对你有用,请随意赞赏

Leave a Comment