先引入jar包
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
int a = 3; //重试次数
Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
//.retryIfExceptionOfType(Exception.class) //捕获指定的需要重试的异常
.retryIfException()//捕获Exception异常
//.retryIfResult(StringUtils::isEmpty) //方法返回值判断 可以与异常捕获一起用 可以分开
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) //重试间隔的策略
.withStopStrategy(StopStrategies.stopAfterAttempt(a))//重试停止的的策略
.withRetryListener(new RetryListener() { //重试之后回调的监听器 每次重试都会回调
@Override
public <Boolean> void onRetry(Attempt<Boolean> attempt) {
if (attempt.hasException() && attempt.getAttemptNumber() == a) { //判断当前重试的次数是否是最后一次
System.err.println("异常了");
}
}
})
.build();
try {
retryer.call(() -> typeInfoService.hello()); //需要执行的方法
} catch (Exception e) {
e.printStackTrace();
}
原理参考:https://blog.csdn.net/varyall/article/details/82748469
回调监听器参考:https://blog.csdn.net/aitangyong/article/details/53894678