Spring 如何在消息侦听器中限制重试次数

Spring How to Limit number of retry in Message listener

我正在使用 spring DefaultJmsListenerContainerFactory 和注释 @JmsListener(destination="test.dev.1") 来监听队列中的消息。我已将确认模式设置为 Session.CLIENT_ACKNOWLEDGE,因此如果在消息处理期间发生任何异常,则会重新传递消息。但是我想限制重新传递消息的次数(重试)?我该怎么做?

这是我的 DefaultJmsListenerContainerFactory 代码:

    @Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory () {
    DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
    factory.setConnectionFactory(jmsConnectionFactory());
    factory.setConcurrency("1");
    factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);

    return factory;
}

这不是 JMS 规范的一部分;它有时可以配置为代理上的策略。

有些解决方案仅适用当您无法控制代理端并且您仍想在您的侦听器应用程序中处理此问题时 - 您可以通过[=14识别消息=]s i,e correlationId 或 jmsID,现在您必须设置一个逻辑,如果指定的唯一 header 值已交付一定时间,则丢弃该消息或将其记录在某处以供参考。

    @JmsListener(destination = "${receiveQueue}", containerFactory = "myFactory")
        public void receiveMessage(Message message, String msg) throws Exception {

            try {

                // start processing the message. I have string message(msg)
               //Message object hold the header with more information about the message


                //throw new Exception("Exception has occoured while trying to process the message : " + msg);
            } catch (Exception e) {

               //in message object, WMQConstants.JMSX_DELIVERY_COUNT hold the count for, how many times the message has been retried
                int currentAttemptCount = message.getIntProperty(WMQConstants.JMSX_DELIVERY_COUNT);
                logger.debug("Current attempt count : "+currentAttemptCount);
                if (currentAttemptCount >= MAX_ATTEMPTS) {
                    logger.error("Max attampt for retry has reached for Message : \n" + message);
                    //Logger message
                    System.exit(0);
                } 
               //else throw exception. it will requeue message.
                throw e;
            }
        }