我的 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)重试,又确保其他异常仍根据重试策略重试? 任何代码示例将不胜感激。 预先感谢!
请参阅另一个构造函数
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
,含义是不重试其余未映射的异常。听起来您需要完全相反:重试所有异常并针对映射执行特定操作。
其他选项是覆盖SimpleRetryPolicy
public class IgnoreFatalErrorSimpleRetryPolicy extends SimpleRetryPolicy {
private static final FatalExceptionStrategy exceptionStrategy =
new ConditionalRejectingErrorHandler.DefaultExceptionStrategy();
public IgnoreFatalErrorSimpleRetryPolicy(int maxAttempts) {
super(maxAttempts);
}
@Override
public boolean canRetry(RetryContext context) {
return !exceptionStrategy.isFatal(context.getLastThrowable()) && super.canRetry(context);
}
}