feign中的Retryer有什么作用

本篇內(nèi)容介紹了“feign中的Retryer有什么作用”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

10年積累的做網(wǎng)站、成都網(wǎng)站制作經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認識你,你也不認識我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有華寧免費網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

本文主要研究一下feign的Retryer

Retryer

feign-core-10.2.3-sources.jar!/feign/Retryer.java

public interface Retryer extends Cloneable {

  /**
   * if retry is permitted, return (possibly after sleeping). Otherwise propagate the exception.
   */
  void continueOrPropagate(RetryableException e);

  Retryer clone();

  class Default implements Retryer {

    private final int maxAttempts;
    private final long period;
    private final long maxPeriod;
    int attempt;
    long sleptForMillis;

    public Default() {
      this(100, SECONDS.toMillis(1), 5);
    }

    public Default(long period, long maxPeriod, int maxAttempts) {
      this.period = period;
      this.maxPeriod = maxPeriod;
      this.maxAttempts = maxAttempts;
      this.attempt = 1;
    }

    // visible for testing;
    protected long currentTimeMillis() {
      return System.currentTimeMillis();
    }

    public void continueOrPropagate(RetryableException e) {
      if (attempt++ >= maxAttempts) {
        throw e;
      }

      long interval;
      if (e.retryAfter() != null) {
        interval = e.retryAfter().getTime() - currentTimeMillis();
        if (interval > maxPeriod) {
          interval = maxPeriod;
        }
        if (interval < 0) {
          return;
        }
      } else {
        interval = nextMaxInterval();
      }
      try {
        Thread.sleep(interval);
      } catch (InterruptedException ignored) {
        Thread.currentThread().interrupt();
        throw e;
      }
      sleptForMillis += interval;
    }

    /**
     * Calculates the time interval to a retry attempt. <br>
     * The interval increases exponentially with each attempt, at a rate of nextInterval *= 1.5
     * (where 1.5 is the backoff factor), to the maximum interval.
     *
     * @return time in nanoseconds from now until the next attempt.
     */
    long nextMaxInterval() {
      long interval = (long) (period * Math.pow(1.5, attempt - 1));
      return interval > maxPeriod ? maxPeriod : interval;
    }

    @Override
    public Retryer clone() {
      return new Default(period, maxPeriod, maxAttempts);
    }
  }

  /**
   * Implementation that never retries request. It propagates the RetryableException.
   */
  Retryer NEVER_RETRY = new Retryer() {

    @Override
    public void continueOrPropagate(RetryableException e) {
      throw e;
    }

    @Override
    public Retryer clone() {
      return this;
    }
  };
}
  • Retryer繼承了Cloneable接口,它定義了continueOrPropagate、clone方法;它內(nèi)置了一個名為Default以及名為NEVER_RETRY的實現(xiàn)

  • Default有period、maxPeriod、maxAttempts參數(shù)可以設(shè)置,默認構(gòu)造器使用的period為100,maxPeriod為1000,maxAttempts為5;continueOrPropagate方法首先判斷attempt是否達到閾值,達到則拋出異常,否則進一步計算interval,然后進行sleep

  • NEVER_RETRY的continueOrPropagate直接拋出異常,而clone方法直接返回當(dāng)前實例

SynchronousMethodHandler

feign-core-10.2.3-sources.jar!/feign/SynchronousMethodHandler.java

final class SynchronousMethodHandler implements MethodHandler {
	//......

  public Object invoke(Object[] argv) throws Throwable {
    RequestTemplate template = buildTemplateFromArgs.create(argv);
    Retryer retryer = this.retryer.clone();
    while (true) {
      try {
        return executeAndDecode(template);
      } catch (RetryableException e) {
        try {
          retryer.continueOrPropagate(e);
        } catch (RetryableException th) {
          Throwable cause = th.getCause();
          if (propagationPolicy == UNWRAP && cause != null) {
            throw cause;
          } else {
            throw th;
          }
        }
        if (logLevel != Logger.Level.NONE) {
          logger.logRetry(metadata.configKey(), logLevel);
        }
        continue;
      }
    }
  }


	//......
}
  • SynchronousMethodHandler的invoke的方法首先使用retryer.clone()創(chuàng)建一個retryer,然后在捕獲到RetryableException的時候,會執(zhí)行retryer.continueOrPropagate(e)

RetryableException

feign-core-10.2.3-sources.jar!/feign/RetryableException.java

public class RetryableException extends FeignException {

  private static final long serialVersionUID = 1L;

  private final Long retryAfter;
  private final HttpMethod httpMethod;

  /**
   * @param retryAfter usually corresponds to the {@link feign.Util#RETRY_AFTER} header.
   */
  public RetryableException(int status, String message, HttpMethod httpMethod, Throwable cause,
      Date retryAfter) {
    super(status, message, cause);
    this.httpMethod = httpMethod;
    this.retryAfter = retryAfter != null ? retryAfter.getTime() : null;
  }

  /**
   * @param retryAfter usually corresponds to the {@link feign.Util#RETRY_AFTER} header.
   */
  public RetryableException(int status, String message, HttpMethod httpMethod, Date retryAfter) {
    super(status, message);
    this.httpMethod = httpMethod;
    this.retryAfter = retryAfter != null ? retryAfter.getTime() : null;
  }

  /**
   * Sometimes corresponds to the {@link feign.Util#RETRY_AFTER} header present in {@code 503}
   * status. Other times parsed from an application-specific response. Null if unknown.
   */
  public Date retryAfter() {
    return retryAfter != null ? new Date(retryAfter) : null;
  }

  public HttpMethod method() {
    return this.httpMethod;
  }
}
  • RetryableException繼承了FeignException,它的構(gòu)造器會接收retryAfter,該參數(shù)可以為null

FeignException

feign-core-10.2.3-sources.jar!/feign/FeignException.java

public class FeignException extends RuntimeException {
	//......

  static FeignException errorReading(Request request, Response response, IOException cause) {
    return new FeignException(
        response.status(),
        format("%s reading %s %s", cause.getMessage(), request.httpMethod(), request.url()),
        cause,
        request.requestBody().asBytes());
  }

	//......
}
  • FeignException定義了errorReading靜態(tài)方法,它創(chuàng)建的是FeignException

ErrorDecoder

feign-core-10.2.3-sources.jar!/feign/codec/ErrorDecoder.java

public interface ErrorDecoder {
	//......

  public static class Default implements ErrorDecoder {

    private final RetryAfterDecoder retryAfterDecoder = new RetryAfterDecoder();

    @Override
    public Exception decode(String methodKey, Response response) {
      FeignException exception = errorStatus(methodKey, response);
      Date retryAfter = retryAfterDecoder.apply(firstOrNull(response.headers(), RETRY_AFTER));
      if (retryAfter != null) {
        return new RetryableException(
            response.status(),
            exception.getMessage(),
            response.request().httpMethod(),
            exception,
            retryAfter);
      }
      return exception;
    }

    private <T> T firstOrNull(Map<String, Collection<T>> map, String key) {
      if (map.containsKey(key) && !map.get(key).isEmpty()) {
        return map.get(key).iterator().next();
      }
      return null;
    }
  }

  static class RetryAfterDecoder {

    static final DateFormat RFC822_FORMAT =
        new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", US);
    private final DateFormat rfc822Format;

    RetryAfterDecoder() {
      this(RFC822_FORMAT);
    }

    RetryAfterDecoder(DateFormat rfc822Format) {
      this.rfc822Format = checkNotNull(rfc822Format, "rfc822Format");
    }

    protected long currentTimeMillis() {
      return System.currentTimeMillis();
    }

    /**
     * returns a date that corresponds to the first time a request can be retried.
     *
     * @param retryAfter String in
     *        <a href="https://tools.ietf.org/html/rfc2616#section-14.37" >Retry-After format</a>
     */
    public Date apply(String retryAfter) {
      if (retryAfter == null) {
        return null;
      }
      if (retryAfter.matches("^[0-9]+$")) {
        long deltaMillis = SECONDS.toMillis(Long.parseLong(retryAfter));
        return new Date(currentTimeMillis() + deltaMillis);
      }
      synchronized (rfc822Format) {
        try {
          return rfc822Format.parse(retryAfter);
        } catch (ParseException ignored) {
          return null;
        }
      }
    }
  }

	//......
}
  • ErrorDecoder提供了Default的默認實現(xiàn),其decode方法會使用RetryAfterDecoder來計算retryAfter值,在該值不為null時會返回RetryableException;RetryAfterDecoder的apply方法會根據(jù)retryAfter來計算retryAfter日期,該retryAfter參數(shù)是從response的名為Retry-After的header讀取而來

小結(jié)

  • Retryer繼承了Cloneable接口,它定義了continueOrPropagate、clone方法;它內(nèi)置了一個名為Default以及名為NEVER_RETRY的實現(xiàn)

  • Default有period、maxPeriod、maxAttempts參數(shù)可以設(shè)置,默認構(gòu)造器使用的period為100,maxPeriod為1000,maxAttempts為5;continueOrPropagate方法首先判斷attempt是否達到閾值,達到則拋出異常,否則進一步計算interval,然后進行sleep

  • NEVER_RETRY的continueOrPropagate直接拋出異常,而clone方法直接返回當(dāng)前實例

“feign中的Retryer有什么作用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

網(wǎng)頁標(biāo)題:feign中的Retryer有什么作用
鏈接地址:http://bm7419.com/article12/igopdc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計公司、App開發(fā)定制網(wǎng)站、ChatGPT小程序開發(fā)、微信小程序

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)