恢复
概述
Recovery
用于恢复,不仅仅限于异常恢复,它的功能更接近于fallback
(通俗来说就是兜底)。它是一个函数式接口,定义如下:
java
public interface Recovery<V> {
V recover(Attempt<V, ?> attempt);
}
其中attempt
是本次重试的上下文,它包含了详细的元数据和执行结果(成功的结果或者异常)。Recovery
被回调必须同时满足下面的前提:
- 当前的
Attempt
是非成功的,没有满足成功条件和返回成功结果 Choice
组件确定不会执行下一次重试(也就是shouldRetryNext()
方法返回false
)Chance
中定义了非空的Recovery
recoverPredicate
也就是恢复条件判断为true
recoverPredicate
也就是恢复条件是BiPredicate
类型,它的具体签名是BiPredicate<Recovery<V>, Attempt<V, ?>>
,第一个参数当表传入的Recovery
实例,第二个参数当表本次重试的上下文。在Chance
中,多个recoverPredicate
之间使用or()
方法连接,类似于这样:
java
BiPredicate<Recovery<V>, Attempt<V, ?>> recoverPredicate = (r, a) -> false;
BiPredicate<Recovery<V>, Attempt<V, ?>> rb1 = ...
this.recoverPredicate = recoverPredicate.or(rb1);
BiPredicate<Recovery<V>, Attempt<V, ?>> rb2 = ...
this.recoverPredicate = recoverPredicate.or(rb2);
最终,这个类似链式结构的recoverPredicate
只要其中有一个条件为true
则最终返回的结果为true
。
用法详解
java
public static void main(String[] args) throws Exception {
Chance<String> chance = Chance.<String, Throwable>newBuilder()
.withNeverRetry()
.withRecoverIfHasException()
.withRecovery(attempt -> "Recovery")
.build();
String v = chance.call(() -> {
throw new RuntimeException("Error");
});
System.out.println(v);
}
上面的代码最终输出结果:
shell
Recovery
上方Chance.Builder
的内置方法withRecoverIfHasException()
相当于:
java
Chance.<String, Throwable>newBuilder()
.withRecoverPredicate((recovery, attempt) -> attempt.hasException())
...