您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用JmsTemplate进行手动确认并从Rabbitmq队列中删除消息

如何使用JmsTemplate进行手动确认并从Rabbitmq队列中删除消息

您没有使用jmstemplate,而是使用SimpleMessageListenerContainer来接收消息。

如果您 使用模板,你将不得不使用的execute方法SessionCallback,因为必须确认其内接收消息的会话的范围内。

但是,使用SimpleMessageListenerContainer,您只需将设置sessionAckNowledgeModeSession.CLIENT_ACKNowLEDGE。参见容器javadocs …

/**
 * Message listener container that uses the plain JMS client API's
 * {@code MessageConsumer.setMessageListener()} method to
 * create concurrent MessageConsumers for the specified listeners.
 *
 * <p>This is the simplest form of a message listener container.
 * It creates a fixed number of JMS Sessions to invoke the listener,
 * not allowing for dynamic adaptation to runtime demands. Its main
 * advantage is its low level of complexity and the minimum requirements
 * on the JMS provider: Not even the ServerSessionPool facility is required.
 *
 * <p>See the {@link AbstractMessageListenerContainer} javadoc for details
 * on ackNowledge modes and transaction options. Note that this container
 * exposes standard JMS behavior for the default "AUTO_ACKNowLEDGE" mode:
 * that is, automatic message ackNowledgment after listener execution,
 * with no redelivery in case of a user exception thrown but potential
 * redelivery in case of the JVM dying during listener execution.
 *
 * <p>For a different style of MessageListener handling, through looped
 * {@code MessageConsumer.receive()} calls that also allow for
 * transactional reception of messages (registering them with XA transactions),
 * see {@link DefaultMessageListenerContainer}.
   ...

使用时jmstemplate,您必须在会话范围内进行工作-这是…

首先,您必须在模板中启用客户端确认…

this.jmstemplate.setSessionAckNowledgeMode(Session.CLIENT_ACKNowLEDGE);

然后,将execute方法SessionCallback…一起使用

Boolean result = this.jmstemplate.execute(session -> {
    MessageConsumer consumer = session.createConsumer(
            this.jmstemplate.getDestinationResolver().resolveDestinationName(session, "bar", false));
    String result = null;
    try {
        Message received = consumer.receive(5000);
        if (received != null) {
            result = (String) this.jmstemplate.getMessageConverter().fromMessage(received);

            // Do some stuff here.

            received.ackNowledge();
            return true;
        }
    }
    catch (Exception e) {
        return false;
    }
    finally {
        consumer.close();
    }
}, true);
其他 2022/1/1 18:24:03 有504人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶