<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
import com.github.rholder.retry.*;
import org.junit.Test;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class RetryTest {
private static Integer i=0;
@Test
public void t1(){
//1 任务
Callable<Integer> callable=new Callable<Integer>() {
@Override
public Integer call() throws Exception {
++i;
System.out.println("i="+i);
if (i>=3){
return i;
}
return null;
}
};
//2 构建重试器
Retryer<Integer> retryer=RetryerBuilder.<Integer>newBuilder()
//当返回结果为 false 时 - 执行重试
.retryIfResult(Objects::isNull)
//当执行核心业务逻辑抛出RuntimeException - 执行重试
.retryIfRuntimeException()
//自定义抛出何种异常时 - 执行重试
.retryIfExceptionOfType(IOException.class)
//每次重试时的时间间隔
.withWaitStrategy(WaitStrategies.fixedWait(2L, TimeUnit.SECONDS))
//重试次数,2次之后就不重试了
.withStopStrategy(StopStrategies.stopAfterAttempt(2))
//每次重试时定义一个监听器listener,监听器的逻辑可以是 "日志记录"、"做一些补偿操作"
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
System.out.println("当前是第 "+attempt.getAttemptNumber()+" 次重试");
}
})
.build();
try {
//3 执行任务
Integer call = retryer.call(callable);
System.out.println(call);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (RetryException e) {
e.printStackTrace();
}
}
}
运行测试用例: