guava-retrying 源码解析(停止策略详解)

一、停止策略相关类

1、停止策略接口:StopStrategy接口,只有一个抽象方法

// 是否应该停止重试。不同的停止策略有不同的实现。
boolean
shouldStop(Attempt failedAttempt);

2、停止策略工厂类:StopStrategies类

  这是一个常量类、工厂类,用于创建停止策略对象。这个工厂类里面定义了三种停止策略,都是常量静态内部类。

  该工厂类是创建停止策略的唯一途径。

二、详解三种停止策略

1、从不停止策略:NeverStopStrategy (默认策略

  使用这种策略,会进行无限次的重试。

2、指定重试次数的策略:StopAfterAttemptStrategy

  这种策略,构造方法里需要传入一个int型的参数,这个参数决定了重试的次数。

3、通过比较延迟时间决定是否重试:StopAfterDelayStrategy

  通过“第一次尝试延迟时间”和创建该策略对象时传入的延迟时间参数进行比较,如代码中的 shouldStop() 方法所示。

  @Test
    public void testStopAfterDelayWithTimeUnit() {
        assertFalse(StopStrategies.stopAfterDelay(1, TimeUnit.SECONDS).shouldStop(failedAttempt(2, 999L)));
        assertTrue(StopStrategies.stopAfterDelay(1, TimeUnit.SECONDS).shouldStop(failedAttempt(2, 1000L)));
        assertTrue(StopStrategies.stopAfterDelay(1, TimeUnit.SECONDS).shouldStop(failedAttempt(2, 1001L)));
    }

    public Attempt<Boolean> failedAttempt(long attemptNumber, long delaySinceFirstAttempt) {
        return new Retryer.ExceptionAttempt<Boolean>(new RuntimeException(), attemptNumber, delaySinceFirstAttempt);
    }

  // --------源码-------
 
  @Override
 
   }