Spring Retry中如何为@Retryable添加基于异常错误码的重试条件?
解决方案
要实现仅针对携带RETRY错误码的CustomException触发重试,有两种常用实现方式,可根据需求复杂度选择:
方案一:使用@Retryable的exceptionExpression属性(简单场景推荐)
Spring Retry 1.2及以上版本支持通过Spring EL表达式,在注解中直接判断异常属性来决定是否触发重试。只需修改@Retryable注解,添加条件判断:
import org.springframework.retry.annotation.Retryable; @Override @Retryable( value = CustomException.class, maxAttempts = 2, // 通过Spring EL判断异常的错误码是否为RETRY exceptionExpression = "#{throwable.errorCode == T(com.yourpackage.CustomErrorCode).RETRY}" ) public void process(String input) { // 业务逻辑 }
注意事项:
- 替换
com.yourpackage为CustomErrorCode枚举实际所在的包路径 - 确保
CustomException类提供getErrorCode()方法,用于获取错误码:
public class CustomException extends RuntimeException { private final CustomErrorCode errorCode; public CustomException(CustomErrorCode errorCode) { super(errorCode.getMessage()); this.errorCode = errorCode; } // 必须提供该方法供EL表达式调用 public CustomErrorCode getErrorCode() { return errorCode; } }
方案二:自定义RetryPolicy(复杂场景推荐)
如果后续需要扩展更多重试判断逻辑,或需要复用判断规则,推荐自定义重试策略:
1. 实现自定义RetryPolicy
继承SimpleRetryPolicy,重写canRetry方法,添加错误码判断逻辑:
import org.springframework.retry.RetryContext; import org.springframework.retry.policy.SimpleRetryPolicy; public class CustomErrorCodeRetryPolicy extends SimpleRetryPolicy { @Override public boolean canRetry(RetryContext context) { Throwable lastThrowable = context.getLastThrowable(); // 仅当异常是CustomException且错误码为RETRY,同时未超过最大重试次数时,允许重试 if (lastThrowable instanceof CustomException) { CustomException customException = (CustomException) lastThrowable; return customException.getErrorCode() == CustomErrorCode.RETRY && super.canRetry(context); } // 其他情况不允许重试 return false; } }
2. 配置RetryTemplate
在配置类中定义带有自定义策略的RetryTemplate Bean:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.retry.annotation.EnableRetry; import org.springframework.retry.support.RetryTemplate; @Configuration @EnableRetry public class RetryConfig { @Bean public RetryTemplate retryTemplate() { RetryTemplate retryTemplate = new RetryTemplate(); CustomErrorCodeRetryPolicy retryPolicy = new CustomErrorCodeRetryPolicy(); // 设置最大重试次数 retryPolicy.setMaxAttempts(2); retryTemplate.setRetryPolicy(retryPolicy); return retryTemplate; } }
3. 在方法上指定使用该RetryTemplate
修改@Retryable注解,指定使用自定义的retryTemplate:
@Override @Retryable(retryTemplate = "retryTemplate") public void process(String input) { // 业务逻辑 }
内容的提问来源于stack exchange,提问作者Vaishnavi Sabnawis
相关产品推荐
相关产品推荐

