Spring Cloud Stream和Spring RetryTemplate对嵌套异常的处理



我有一个使用Kafka绑定器的Spring Cloud Stream项目,我想添加重试功能,我正在尝试使用RetryTemplate并指定我想处理的某些异常,但由于任何异常都由MessageTransformationException包装,我无法以我想要的方式配置它。有没有一种方法可以处理嵌套的异常?

重试模板

@StreamRetryTemplate
public RetryTemplate myRetryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();

ExceptionClassifierRetryPolicy exceptionClassifierRetryPolicy =
new ExceptionClassifierRetryPolicy();
Map<Class<? extends Throwable>, RetryPolicy> policyMap = new HashMap<>();
policyMap.put(MyException.class, new SimpleRetryPolicy(4));
exceptionClassifierRetryPolicy.setPolicyMap(policyMap);
retryTemplate.setRetryPolicy(exceptionClassifierRetryPolicy);
return retryTemplate;
}

Stacktrace

org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message in bean '...' for component ‘...'; nested exception is org.springframework.messaging.MessageHandlingException: error occurred during processing message in 'MethodInvokingMessageProcessor' [org.springframework.integration.handler.MethodInvokingMessageProcessor@4dba2d07]; nested exception is MyException

所以它忽略了我为MyException 设置的配置

您需要在SimpleRetryPolicy中将traverseCauses设置为true

/**
* Create a {@link SimpleRetryPolicy} with the specified number of retry attempts. If
* traverseCauses is true, the exception causes will be traversed until a match is
* found.
* @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 is this cause traversable
*/
public SimpleRetryPolicy(int maxAttempts, Map<Class<? extends Throwable>, Boolean> retryableExceptions,
boolean traverseCauses) {

因此:

new SimpleRetryPolicy(4, Collections.singletonMap(Exception.class, true), true);

最新更新