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

Spring Cloud Stream and Spring RetryTemplate handling of nested exception

我有一个使用 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;
}

堆栈跟踪

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);