Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the function of Retryer in feign

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what is the role of Retryer in feign". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Order

This paper mainly studies the Retryer of feign.

Retryer

FeignMuscoreMush10.2.3Muthsources.jarwoods UniplicityRetryer.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 inherits the Cloneable interface, which defines continueOrPropagate and clone methods; it has a built-in implementation called Default and an implementation named NEVER_RETRY

Default has period, maxPeriod and maxAttempts parameters that can be set. The default constructor uses a period of 100MagneMaxPeriod, 1000MenMaxAttempts and 5continueOrPropagate. The method first determines whether the attempt has reached the threshold, and throws an exception if it reaches the threshold. Otherwise, the interval is further calculated, and then the sleep is performed.

The continueOrPropagate of NEVER_RETRY directly throws an exception, while the clone method directly returns the current instance

SynchronousMethodHandler

FeignMethodHandler.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's invoke method first creates a retryer using retryer.clone (), and then executes retryer.continueOrPropagate (e) when the RetryableException is captured

RetryableException

FeignMuscoremuri 10.2.3Muthsources.jarroommax 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 inherits FeignException, and its constructor receives retryAfter, which can be null.

FeignException

FeignMuscoreMush10.2.3Muthsources.jarroommax 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 defines the errorReading static method, which creates a FeignException

ErrorDecoder

FeignMuscoremuri 10.2.3Muthsources.jarhammer Universe feignAccording 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 (response.headers (), RETRY_AFTER)) If (retryAfter! = null) {return new RetryableException (response.status (), exception.getMessage (), response.request (). HttpMethod (), exception, retryAfter);} return exception } private T 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 provides a default implementation of Default, and its decode method uses RetryAfterDecoder to calculate the retryAfter value. If the value is not null, the apply method that returns RetryableException;RetryAfterDecoder calculates the retryAfter date based on retryAfter, and the retryAfter parameter is read from the header named response.

Summary

Retryer inherits the Cloneable interface, which defines continueOrPropagate and clone methods; it has a built-in implementation called Default and an implementation named NEVER_RETRY

Default has period, maxPeriod and maxAttempts parameters that can be set. The default constructor uses a period of 100MagneMaxPeriod, 1000MenMaxAttempts and 5continueOrPropagate. The method first determines whether the attempt has reached the threshold, and throws an exception if it reaches the threshold. Otherwise, the interval is further calculated, and then the sleep is performed.

The continueOrPropagate of NEVER_RETRY directly throws an exception, while the clone method directly returns the current instance

This is the end of the content of "what is the function of Retryer in feign". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report