Skip to content

Wait 组件

概述

Wait用于计算下一轮重试执行之前的等待时间。它是一个函数式接口,定义如下:

java
public interface Wait<V, E extends Throwable> {

    long computeWaitDuration(Attempt<V, E> attempt);
}

其中attempt是本次重试的上下文,它包含了详细的元数据和执行结果(成功的结果或者异常),返回值表示下一轮重试执行之前的等待时间,单位是毫秒。Chance提供多个Wait的内置实现:

  • NoWait:返回值为0,这是默认启用的实现
  • CompositeWait:组合多个Wait实例,按添加的顺序执行
  • FixedWait:通过配置固定的时间间隔作为等待时间,这是最常用的一个实现
  • RandomWait:通过随机选择指定最小和最大时间间隔之间的一个随机值作为等待时间,通俗理解就是random[minDuration, maxDuration)
  • IncrementingWait:通过增量计算公式确定等待时间,计算公式是initialDuration + (attemptTimes - 1) * increasedDuration,其中attemptTimes为当前重试次数
  • ExponentialBackOffWait:通过指数退避算法计算等待时间,计算公式是min(maxDuration , round(base ^ attemptTimes * multiplier)),其中attemptTimes为当前重试次数,base的默认值为2maxDuration用于限制等待时间的最大值
  • FibonacciBackoffWait:通过斐波那契算法计算等待时间,计算公式是 min(maxDuration , round(fibonacci(attemptTimes) * multiplier)),其中attemptTimes为当前重试次数,maxDuration用于限制等待时间的最大值

当使用的Wait实例数量大于 1,Chance建造者默认会把所有添加到其中的Wait实例封装到一个CompositeWait之中,并且此CompositeWait最终计算得到的等待时间是其中所有Wait实例计算结果的总和。如果内置的Wait实现不能满足实际场景的需求,,可以通过实现Wait接口定制所需的Wait组件。

使用 Wait

java
Chance<String> c1 = Chance.<String, Throwable>newBuilder()
        // 固定重试等待时间为1000 ms
        .withFixedWaitTime(1000L, TimeUnit.MILLISECONDS)
        .build();

// 上面的代码可以写成下面这样,效果是等价的
Chance<String> c2 = Chance.<String, Throwable>newBuilder()
        .withWait(Wait.newFixedWait(1000L))
        .build();

// 使用自定义Wait实现
Chance<String> c3 = Chance.<String, Throwable>newBuilder()
        .withWait(new CustomWait())
        .build();

class CustomWait implements Wait<String, Throwable> {

    @Override
    public long computeWaitDuration(Attempt<String, Throwable> attempt) {
        // impl computeWaitDuration method
        return 0L;
    }
}

贡献者

页面历史

Released under the MIT License.