有些业务场景需要重试多次,比如请求第三方api,可能会遇到一些未知的问题,这时候会尝试重试请求
Maven的pom配置
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
简单运用例子
package demo.controller;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.github.rholder.retry.RetryException;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.base.Predicates;
public class Test {
public static void main(String[] args) {
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfResult(Predicates.equalTo(true))// 设置自定义段元重试源
.retryIfExceptionOfType(Exception.class)// 设置异常重试源
.retryIfRuntimeException()// 设置异常重试源
.withStopStrategy(StopStrategies.stopAfterAttempt(3))// 设置重试2次,同样可以设置重试超时时间
.withWaitStrategy(WaitStrategies.fixedWait(5L, TimeUnit.SECONDS))// 设置每次重试间隔,5秒
.build();
try {
retryer.call(new Callable<Boolean>() {// 使用重试器执行你的业务
int i = 0;
@Override
public Boolean call() throws Exception {
i++;
System.out.printf("第"+i+"次执行!");
count();
if (i<2) {
System.out.printf("执行失败!");
throw new IOException("异常");
}
System.out.printf("执行成功!");
return true;
}
});
} catch (RetryException e) {
System.out.printf("超过重试次数"+ e);
} catch (ExecutionException e) {
System.out.printf("重试框架异常"+ e);
}
}
protected static void count() {//业务方法
System.out.printf("方法执行");
}
}