【二三方】_Retryer重试器原理与使用

Retryer重试器原理与使用

  • Retryer重试器常用于发送http请求时,针对网络抖动、特定响应等情况,设置重新发送http请求。

  • Retryer使用步骤:

    • 1.引入Maven依赖:

      1
      2
      3
      4
      5
      <dependency>
      <groupId>com.github.rholder</groupId>
      <artifactId>guava-retrying</artifactId>
      <version>2.0.0</version>
      </dependency>
    • 2.创建重试器对象:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
      .retryIfException()
      .retryIfResult((resp) -> {
      if (resp == null || StringUtils.isEmpty(resp)) {
      rechargeThirdLog(thirdRechargeOrderRBO, "HTTP_RETRY", checkUrl, headers, params, resp, "重试");
      return true;//返回true表示重试
      }
      return false;//返回false表示不重试
      })
      .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
      .withStopStrategy(StopStrategies.stopAfterAttempt(3))
      .build();
    • 3.创建重试任务,因为该任务一般都具有返回值,所以通过实现Callable接口来创建任务:

      1
      2
      3
      4
      5
      Callable<Boolean> callable = new Callable<Boolean>() {
      public Boolean call() throws Exception {
      return HttpUtil.postRequest(checkUrl, headers, params);
      }
      };
    • 4.使用重试器执行任务:

      1
      String resp = retryer.call(callable);
  • Retryer常见属性

    • .retryIfException():任务抛出runtime异常、checked异常时都会重试,但是抛出error不会重试;

    • .retryIfResult(s -> Objects.equals(s, null)):任务方法返回值为空时重试;

    • .retryIfResult参数中除了返回重试与否,还可以添加其他逻辑,如下添加了打印日志的代码:

      1
      2
      3
      4
      5
      6
      7
      .retryIfResult((resp) -> {
      if (resp == null || StringUtils.isEmpty(resp)) {
      rechargeThirdLog(thirdRechargeOrderRBO, "HTTP_RETRY", checkUrl, headers, params, resp, "重试");
      return true;//返回true表示重试
      }
      return false;//返回false表示不重试
      })
    • .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)):每次失败之后等待1秒再重试;

    • .withStopStrategy(StopStrategies.stopAfterAttempt(3)):最大重试次数为3。