guava-retrying提供了WaitStrategy接口,用来控制2次重试的时间间隔,这个接口与StopStrategy有的类似。内置的等待策略在WaitStrategies中定义。
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
public class AlwaysExceptionTask implements Callable<Boolean> {
private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
private int times = 1;
@Override
public Boolean call() throws Exception {
System.out.println(df.format(new Date()));
int thisTimes = times;
times++;
if (thisTimes == 1) {
throw new NullPointerException();
} else if (thisTimes == 2) {
throw new IOException();
} else if (thisTimes == 3) {
throw new ArithmeticException();
} else {
throw new Exception();
}
}
}
WaitStrategies.noWait()失败后立刻重试,没有等待时间。
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfException()
.withWaitStrategy(WaitStrategies.noWait())
.build();
System.out.println("begin..." + df.format(new Date()));
try {
retryer.call(new AlwaysExceptionTask());
} catch (Exception e) {
System.err.println("still failed after retry." + e.getCause().toString());
}
System.out.println("end..." + df.format(new Date()));
WaitStrategies.fixedWait(1, TimeUnit.SECONDS)间隔固定时间之后重试,比如每隔1s重试一次。
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfException()
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
.build();
System.out.println("begin..." + df.format(new Date()));
try {
retryer.call(new AlwaysExceptionTask());
} catch (Exception e) {
System.err.println("still failed after retry." + e.getCause().toString());
}