Introduction
spring-retry的官方说明:
Retry and backoff policies of retryable operations.
To make processing more robust and less prone to failure, it sometimes helps to automatically retry a failed operation in case it might succeed on a subsequent attempt. Errors that are susceptible to intermittent failure are often transient in nature.
spring-retry原先是spring-batch的一部分,后来单独成为一个项目了。
该项目maven坐标如下:
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
spring-retry的两种使用方式:
- 基于注解:spring-retry利用spring-aop对注解了特定注解的方法做代理拦截实现重试机制,重试过程中包含了重试、退避、断路器、恢复等操作,分别对应了注解:
@Retryable
@Backoff
@CurcuitBreaker
@Recover
- 编码调用:使用
RetryTemplate
执行
案例
注解方式
@Configuration
@EnableRetry
public class Application {
}
@Service
class Service {
@Retryable(RemoteAccessException.class)
public void service() {
// ... do something
}
@Recover
public void recover(RemoteAccessException e) {
// ... panic
}
}
调用service方法如果抛出RemoteAccessException
则默认重试执行3次,之后再去执行recover方法。同时@Retryable
可以设置异常类型、重试次数、退避策略。
RetryTemplate方式
RetryTemplate template = RetryTemplate.builder()
.maxAttempts(3)
.fixedBackoff(1000)
.retryOn(RemoteAccessException.class)
.build();
template.execute(ctx -> {
// ... do something
});
实现原理
注解调用原理
基于注解方式调用整体实现方式如下图: