public static void main(String[] args) throws Exception{
try{
Retryer<Boolean> retryer = RetryerBuilder
.<Boolean>newBuilder()
.retryIfException()
.retryIfResult(aBoolean -> Objects.equals(aBoolean, false))
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
boolean result = retryer.call(() -> test());
if (result){
System.out.println("retryer OK");
}
}catch (Exception e){
System.out.println("超过重试次数依然异常");
throw new Exception();
}
}
private static boolean test(){
System.out.println(111111);
throw new RuntimeException();
}
retryIfException retryIfException,抛出 runtime 异常、checked 异常时都会重试,但是抛出 error 不会重试。
retryIfRuntimeException retryIfRuntimeException 只会在抛 runtime 异常的时候才重试,checked 异常和error 都不重试。
retryIfExceptionOfType retryIfExceptionOfType 允许我们只在发生特定异常的时候才重试,比如NullPointerException 和 IllegalStateException 都属于 runtime 异常,也包括自定义的error。
fixedWait 如果发生异常重试等待时间
stopAfterAttempt 异常出现后的重试次数