Maven配置
<!-- resilience4j -->
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-retry</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
<version>1.7.0</version>
</dependency>
<!-- resilience spring boot integration with annotation requires spring aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
使用@Retry注解方式集成
使用编程方式集成
MyRetry.java
public class MyRetry{
/**
* 对Retry方法进行封装
*
**/
public <T> T doSomethingWithRetry(int attempts, RetryFunction<T> function, RetryRecoverFunction<T> recoverFunction){
//建立Retry配置
RetryConfig config = RetryConfig.custom()
.maxAttempts(attempts) //尝试次数
.waitDuration(Duration.ofMillis(100))//每次重试的等待时间(毫秒)
.build();
//创建Retry对象
Retry retry = Retry.of("myRetry", config);
//把要运行的方法封装为CheckedFunction
CheckedFunction0<T> f = Retry.decorateCheckedSupplier(
retry, () -> {
return function.invoke();
});
//设置重试的Recover方法。这个方法只有在所有重试次数都用完之后才会被调用
return Try.of(f).recover(throwable -> {
if(recoverFunction != null){
return recoverFunction.invoke(throwable);
}
return null;
}).getOrElse(() -> null);
}
}
使用上述这个封装
MyRetry myRetry;
//...
public void doSomething(){
// ...
myRetry.doSomethingWithRetry(3, () -> {
//写一些会抛异常的代码
});
// ...
}