官方文档地址: https://github.com/rholder/guava-retrying
public static void main(String[] args) {
Callable<Boolean> callable = new Callable<Boolean>() {
private int i = 1;
public Boolean call() throws Exception {
// do something useful here
System.out.println("......" + i);
if (i==1){
i ++ ;
throw new NullPointerException();
}
if (i == 2){
return true;
}
return true;
}
};
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
// 如果Callable结果为null,继续重试
.retryIfResult(Predicates.<Boolean>isNull())
// IOException,继续重试
.retryIfExceptionOfType(IOException.class)
// RuntimeException,继续重试
.retryIfRuntimeException()
// 指定重试策略,重试三次后停止
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
try {
Boolean call = retryer.call(callable);
System.out.println("call: " + call);
} catch (RetryException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
打印结果
......1
......2 // 第二次成功
call: true // 打印callable的返回值
稍微修改一下代码
public static void main(String[] args) {
Callable<String> callable = new Callable<String>() {
private int i = 1;
public String call() throws Exception {
// do something useful here
System.out.println("......" + i);
if (i==1){
i ++ ;
throw new NullPointerException();
}
if (i == 2){
i ++ ;
return "error";
}
return "ok";
}
};
Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
// 如果返回结果是error,继续重试
.retryIfResult(Predicates.equalTo("error"))
.retryIfExceptionOfType(IOException.class)
.retryIfRuntimeException()
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
try {
String call = retryer.call(callable);
System.out.println("call: " + call);
} catch (RetryException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
打印结果
......1
......2 // 结果是error
......3 // 第三次成功
call: ok
重试的方法需要包装到Callable接口当中, 方法很多的话使用起来稍有不便,
可以使用AOP的方式来使用Retry
具体可以参考龙潭斋大神("http://techlog.cn")的这篇
http://www.techlog.cn/article/list/10183169