Spring如何限制Message侦听器中的重试次数

时间:2015-10-20 17:23:50

标签: spring jms spring-jms

我正在使用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;
}

3 个答案:

答案 0 :(得分:2)

这不是JMS规范的一部分;它有时可以配置为经纪人的政策。

答案 1 :(得分:0)

当您无法控制代理端并且仍希望在侦听器应用程序中处理此问题时,某些解决方案仅适用 - 您可以按标头i,e correlationId或jmsID识别消息,现在你必须设置一个逻辑,如果指定的唯一标头值已经传送了一段时间,那么丢弃该消息或将其记录在某处以供参考。

答案 2 :(得分:0)

    @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;
            }
        }