httpClient 是通过 retryHandler 来实现重试的。当请求过程出现异常时,你可以选择是否自动重试

1:使用默认的重试策略(不推荐)
CloseableHttpClient httpClient = HttpClients.custom()
                .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true))
                .build();
  • 1.
  • 2.
  • 3.

初始化client客户端时设置 RetryHandler 为DefaultHttpRequestRetryHandler,第一个参数3为重试的次数,第二个参数为调用成功后是否继续重试,这里配置的是继续(常规设置为false即可),该方法最大的缺点为触发重试的异常类型固定,适合的业务场景单一

2: 自定义重试策略(推荐)
定义重试策略
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

  public boolean retryRequest(
          IOException exception,
          int executionCount,
          HttpContext context) {
      System.out.println(Thread.currentThread().getName()+ " try request: " + executionCount);
      if (executionCount >= 5) {
          // Do not retry if over max retry count
          return false;
      }
      if (exception instanceof InterruptedIOException) {
          // Timeout
          return false;
      }
      if (exception instanceof UnknownHostException) {
          // Unknown host, 通常不用重试,这里暂时返回 true 测试使用
          return true;
      }
      if (exception instanceof ConnectTimeoutException) {
          // Connection refused
          return false;
      }
      if (exception instanceof SSLException) {
          // SSL handshake exception
          return false;
      }
      HttpClientContext clientContext = HttpClientContext.adapt(context);
      HttpRequest request = clientContext.getRequest();
      boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
      if (idempotent) {
          // Retry if the request is considered idempotent
          return true;
      }
      return false;
  }

};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.

该方法通过添加控制返回值的逻辑,灵活变更触发重试的异常

初始化客户端
CloseableHttpClient httpclient = HttpClients.custom()
      .setRetryHandler(myRetryHandler)
      .build();
  • 1.
  • 2.
  • 3.