如何使用SimpleRetryPolicy从Spring AMQP重试策略中排除特定异常?

dluptydi  于 2023-03-07  发布在  Spring
关注(0)|答案(1)|浏览(203)

我在Spring AMQP应用程序中有一个RabbitListener,我使用的是一个自定义的RabbitListenerFactory,它配置了一个SimpleRetryPolicy用于消息重试。但是,我希望排除某些异常,使其不被重试。目前,我的配置如下所示:

@Bean
fun retryPolicy(): SimpleRetryPolicy {
    val exceptions = mutableMapOf<Class<out Throwable>, Boolean>(
        ValidationException::class.java to false,
        IllegalArgumentException::class.java to false,
        EntityNotFoundException::class.java to false,
    )
    return SimpleRetryPolicy(6, exceptions, true)
}

@Bean
fun retryInterceptor(customMessageRecoverer: CustomMessageRecoverer): RetryOperationsInterceptor? {
    return RetryInterceptorBuilder.stateless().retryPolicy(retryPolicy())
        .backOffOptions(1000, 2.0, 5000)
        .recoverer(customMessageRecoverer)
        .build()
}

@Bean
fun myFactory(
    configurer: SimpleRabbitListenerContainerFactoryConfigurer,
    connectionFactory: ConnectionFactory,
    customsMessageRecoverer: CustomMessageRecoverer,
): SimpleRabbitListenerContainerFactory {
    val factory = SimpleRabbitListenerContainerFactory()
    configurer.configure(factory, connectionFactory)
    factory.setAdviceChain(workMessagesRetryInterceptor(customsMessageRecoverer))
    return factory;
}

然而,我注意到,使用这个配置,根本不会执行重试,即使是对于不在排除列表中的异常。我如何修改这个配置,既排除特定的异常重试,如AuthoraizationException或IllegalArgumentException,又确保其他异常仍然根据重试策略重试?任何代码示例都将受到欢迎。提前感谢!

jgovgodb

jgovgodb1#

查看SimpleRetryPolicy的另一个构造函数:

/**
 * Create a {@link SimpleRetryPolicy} with the specified number of retry attempts. If
 * traverseCauses is true, the exception causes will be traversed until a match or the
 * root cause is found. The default value indicates whether to retry or not for
 * exceptions (or super classes thereof) that are not found in the map.
 * @param maxAttempts the maximum number of attempts
 * @param retryableExceptions the map of exceptions that are retryable based on the
 * map value (true/false).
 * @param traverseCauses true to traverse the exception cause chain until a classified
 * exception is found or the root cause is reached.
 * @param defaultValue the default action.
 */
public SimpleRetryPolicy(int maxAttempts, Map<Class<? extends Throwable>, Boolean> retryableExceptions,
        boolean traverseCauses, boolean defaultValue) {

在您的情况下,defaultValue被设置为false,意味着不重试其余未Map的异常。重试所有异常,并对mapped执行特定操作。

相关问题