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
的默认值为2
,maxDuration
用于限制等待时间的最大值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;
}
}