命令式
概述
可以通过建造者Chance.Builder
来命令式构造Chance
实例,然后再基于Chance
实例去调用需要重试的函数。
用法详解
java
public static void main(String[] args) {
// 通过建造者构造Chance实例
Chance<String> chance = Chance.<String, Throwable>newBuilder()
// 最大重试次数为3
.withMaxRetryTimes(3)
// 当执行的函数抛出RuntimeException的时候进行重试
.withRetryableExceptions(Collections.singletonMap(RuntimeException.class, Boolean.TRUE))
.build();
try {
String r = chance.call(() -> "No Exceptions");
System.out.println(r);
} catch (ChanceException ignore) {
}
// Chance实例可以复用
AtomicInteger times = new AtomicInteger();
String r = "Init";
try {
r = chance.call(() -> {
times.incrementAndGet();
throw new RuntimeException("Error");
});
} catch (ChanceException ignore) {
}
System.out.printf("重试[%d]次,结果: %s\n", times.get(), r);
}
上面的代码最终输出结果:
shell
No Exceptions
重试[3]次,结果: Init
TIP
更多的预定义的条件可以参考内置条件小节。