监听器
概述
监听器用于监听Attempt
的状态变化,目前在执行流程中有两个节点会回调监听器:
- 当前的
Attempt
初始化完成之后,用于接收Attempt
的属性,以及提供主动取消当前重试的操作 - 当前的
Attempt
接收到结果或者异常之后
监听器也设计成一个函数式接口,它的定义如下:
java
public interface Listener<V, E extends Throwable> {
void onFire(Attempt<V, E> attempt);
}
使用 Listener
java
public static void main(String[] args) throws Exception {
Chance<String> c1 = Chance.<String, Throwable>newBuilder()
.withNeverRetry()
.withListener(attempt -> {
System.out.printf("Attempt state => %s\n", attempt.state());
})
.build();
c1.call(() -> "Ok");
c1.call(() -> {
throw new RuntimeException("Error");
});
}
上面的代码最终输出结果:
shell
Attempt state => RUNNING
Attempt state => SUCCESS
Attempt state => RUNNING
Attempt state => FAILED
Exception in thread "main" cn.vlts.chance.ChanceException: Retrying calling failed after 1 attempts. Exception message: Error.
// ...... 省略大量异常栈信息
取消重试
Chance
提供主动取消重试的功能,但是考虑到执行流程的正确性,取消重试的窗口在当前的重试上下文Attempt
初始化完成之后以及真实的调用执行之前,目前只能通过监听器回调实现。见下面的例子:
java
public static void main(String[] args) throws Exception {
Chance<String> chance = Chance.<String, Throwable>newBuilder()
.withRetryForever()
.withListener(attempt -> {
if (attempt.attemptTimes() > 1 && Objects.equals(attempt.state(), Attempt.State.RUNNING)) {
boolean cancel = attempt.cancel();
System.out.printf("Cancel attempt => %s\n", cancel);
}
})
.build();
chance.call(() -> {
throw new RuntimeException("Error");
});
}
上面的代码最终输出结果:
shell
Cancel attempt => true
Exception in thread "main" cn.vlts.chance.ChanceException: Retrying calling failed after 2 attempts.
Exception message: Attempt canceled.