如何在RabbitMQ中实现重试逻辑?

e7arh2l6  于 2022-11-08  发布在  RabbitMQ
关注(0)|答案(1)|浏览(995)

在我的项目中,我设置了SimpleRetryPolicy来添加自定义异常和使用此策略的RetryOperationsInterceptor

@Bean
    public SimpleRetryPolicy rejectionRetryPolicy() {
        Map<Class<? extends Throwable>, Boolean> exceptionsMap = new HashMap<Class<? extends Throwable>, Boolean>();
        exceptionsMap.put(DoNotRetryException.class, false);//not retriable
        exceptionsMap.put(RetryException.class, true); //retriable
        return new SimpleRetryPolicy(3, exceptionsMap, true);
    }

    @Bean
    RetryOperationsInterceptor interceptor() {
        return RetryInterceptorBuilder.stateless()
                .retryPolicy(rejectionRetryPolicy())
                .backOffOptions(2000L, 2, 3000L)
                .recoverer(
                        new RepublishMessageRecoverer(rabbitTemplate(), "dlExchange", "dlRoutingKey"))
                .build();
    }

但是,使用这些配置,重试对于RetryException和DoNotRetryException都不起作用,我希望RetryException重试有限次,DoNotRetryException发送到DLQ
请帮助的问题,我附上回购链接,如果在需要的情况下。
https://github.com/aviralnimbekar/RabbitMQ/tree/main/src

2wnc66cl

2wnc66cl1#

您的GlobalErrorHandler在重试发生之前执行其逻辑,并且您用AmqpRejectAndDontRequeueException覆盖了那里的异常。看起来您在那里执行了到DLX的发布。请考虑将您的GlobalErrorHandler逻辑移动到factory.setErrorHandler();的更通用的ErrorHandler
更多信息请参阅文档:https://docs.spring.io/spring-amqp/reference/html/#exception-handling

更新

在从您的@RabbitListener中删除errorHandler = "globalErrorHandler"后,我在日志中得到了以下内容:

2022-08-03 16:02:08.093  INFO 16896 --- [nio-8080-exec-4] c.t.r.producer.RabbitMQProducer          : Message sent -> retry
2022-08-03 16:02:08.095  INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer          : Retrying message...
2022-08-03 16:02:10.096  INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer          : Retrying message...
2022-08-03 16:02:13.099  INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer          : Retrying message...
2022-08-03 16:02:13.100  WARN 16896 --- [ntContainer#0-1] o.s.a.r.retry.RepublishMessageRecoverer  : Republishing failed message to exchange 'dlExchange' with routing key dlRoutingKey
2022-08-03 16:02:17.736  INFO 16896 --- [nio-8080-exec-5] c.t.r.producer.RabbitMQProducer          : Message sent -> 1231231
2022-08-03 16:02:17.738  INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer          : sending into dlq...
2022-08-03 16:02:17.739  WARN 16896 --- [ntContainer#0-1] o.s.a.r.retry.RepublishMessageRecoverer  : Republishing failed message to exchange 'dlExchange' with routing key dlRoutingKey

这绝对反映了你最初的要求。

相关问题