扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
本篇内容介绍了“feign中的Retryer有什么作用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
10年积累的做网站、成都网站制作经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有华宁免费网站建设让你可以放心的选择与我们合作。
本文主要研究一下feign的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.
* 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方法;它内置了一个名为Default以及名为NEVER_RETRY的实现
Default有period、maxPeriod、maxAttempts参数可以设置,默认构造器使用的period为100,maxPeriod为1000,maxAttempts为5;continueOrPropagate方法首先判断attempt是否达到阈值,达到则抛出异常,否则进一步计算interval,然后进行sleep
NEVER_RETRY的continueOrPropagate直接抛出异常,而clone方法直接返回当前实例
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()创建一个retryer,然后在捕获到RetryableException的时候,会执行retryer.continueOrPropagate(e)
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,它的构造器会接收retryAfter,该参数可以为null
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静态方法,它创建的是FeignException
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; } privateT firstOrNull(Map > 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 * Retry-After format */ 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的默认实现,其decode方法会使用RetryAfterDecoder来计算retryAfter值,在该值不为null时会返回RetryableException;RetryAfterDecoder的apply方法会根据retryAfter来计算retryAfter日期,该retryAfter参数是从response的名为Retry-After的header读取而来
Retryer继承了Cloneable接口,它定义了continueOrPropagate、clone方法;它内置了一个名为Default以及名为NEVER_RETRY的实现
Default有period、maxPeriod、maxAttempts参数可以设置,默认构造器使用的period为100,maxPeriod为1000,maxAttempts为5;continueOrPropagate方法首先判断attempt是否达到阈值,达到则抛出异常,否则进一步计算interval,然后进行sleep
NEVER_RETRY的continueOrPropagate直接抛出异常,而clone方法直接返回当前实例
“feign中的Retryer有什么作用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流