Skip to content

恢复

概述

Recovery用于恢复,不仅仅限于异常恢复,它的功能更接近于fallback(通俗来说就是兜底)。它是一个函数式接口,定义如下:

java
public interface Recovery<V> {

    V recover(Attempt<V, ?> attempt);
}

其中attempt是本次重试的上下文,它包含了详细的元数据和执行结果(成功的结果或者异常)。Recovery被回调必须同时满足下面的前提:

  1. 当前的Attempt是非成功的,没有满足成功条件和返回成功结果
  2. Choice组件确定不会执行下一次重试(也就是shouldRetryNext()方法返回false
  3. Chance中定义了非空的Recovery
  4. 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())
        ...

贡献者

页面历史

Released under the MIT License.