添加依赖
implementation "org.springframework.retry:spring-retry"
启用重试
添加注解 @EnableRetry
在代码上添加注解
@Service
public class TestService {
private static final Logger log = LoggerFactory.getLogger(TestService.class);
@Retryable(
// 最大重试次数,使用耗尽会触发 Recover(如果有配置)
maxAttempts = 4,
// backoff 重试策略
backoff = @Backoff(delay = 1000, maxDelay = 1500),
// 触发指定异常开始重试
value = ArithmeticException.class)
public void compute(int c) throws ArithmeticException {
log.info("compute: {} {}", c, DateFormat.getTimeInstance().format(new Date()));
System.out.println(c / 0);
}
// Recover 表示重试失败后交给用户执行逻辑
// 异常需要在第一个参数
@Recover
public void recover(ArithmeticException e, int c) {
log.info("recover: {}", c, e);
}
}
如果使用Recover注解,需要和被调用方拥有相同参数和返回值
当重试次数耗尽后,会通过Recover定义的方法返回结果
重试的过程是同步进行的
有状态的重试
Retryable 注解设置 stateful = true
需要配置 RetryContextCache
调用方需要自己捕获异常然后再次调用,框架会记录重试次数