Official website: https://github.com/rholder/guava-retrying
Maven:https://mvnrepository.com/artifact/com.github.rholder/guava-retrying
The following examples are spring boot-based, but can be used for spring projects. Currently the latest version is 2.0.0.
Integration steps:
Pom Introduction:
<!--https://mvnrepository.com/artifact/com.github.rholder/guava-retrying - <Dependency> <groupId>Com.github.rholder</groupId> <Artifactid>Guava-retrying</Artifactid> <version>2.0.0</version> </Dependency>
operates directly within a class, based on an anonymous inner class implementation.
PackageCom.jsoft.springboottest.springboottest1.controller;Importjava.io.IOException;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.TimeUnit;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;Importcom.github.rholder.retry.RetryException;ImportCom.github.rholder.retry.Retryer;ImportCom.github.rholder.retry.RetryerBuilder;Importcom.github.rholder.retry.StopStrategies;Importcom.github.rholder.retry.WaitStrategies;Importcom.google.common.base.Predicates; @RestController Public classTestController {Private Static FinalLogger Logger = Loggerfactory.getlogger (TestController.class); @RequestMapping ("/show") PublicString Show () { Retryer <Boolean> retryer = Retryerbuilder.<boolean>newbuilder (). Retryifresult (predicates.< Boolean>isnull ())//Set custom segment element retry source. Retryifexceptionoftype (Exception.class)//Set the exception retry source. retryi Fruntimeexception ()//Set the exception retry source. Withstopstrategy (Stopstrategies.stopafterattempt (5))//Set retry 5 times, also set retry time-out . Withwaitstrategy (Waitstrategies.fixedwait (5L, timeunit.seconds))//Set each retry interval, 5 seconds. Build (); try {retryer.call (new callable<boolean> () {int i = 0; @Override public Boolean Call () throws Exception {i++; Logger.info ("{} Times execution! ", i); Do something if (i<6) {//Analog error 2 times logger.info ("Emulation execution failed! "); throw new IOException ("exception"); } logger.info ("Simulation executed successfully! "); return true; } }); } catch (Retryexception e) {logger.info ("exceeds retry count", e); } catch (Executionexception e) {logger.info ("Retry Framework exception", e); } return"Hello World"; }}
Example Project: HTTPS://GITHUB.COM/EASONJIM/5_JAVA_EXAMPLE/TREE/MASTER/SPRINGBOOTTEST/SPRINGBOOTTEST5
Detailed Description:
Usage Scenarios
In daily development, we often encounter scenarios where external services and interfaces need to be invoked. External services are generally unreliable for callers, especially in the case of poor network conditions, where network jitter can easily lead to exceptional conditions such as request timeouts, which need to be re-invoked using the failed retry policy to retrieve the API interface. The retry policy is also widely used in service governance, with timed detection to see if the service is Alive (Active).
The guava retrying is a flexible, easy-to-retry component that contains a variety of retry strategies and is easy to extend.
In the words of the author:
This was a small extension to Google's guava library to allow for the creation of configurable retrying strategies for a A rbitrary function call, such as something, this talks to a remote service with flaky uptime.
With guava-retrying you can customize to perform retries, as well as monitor the results and behavior of each retry, and the most important guava style-based retry method is really handy.
code example
The following is a simple list guava-retrying
of how to use:
If thrown IOException
then retry, if the return result is null
equal to 2 retry, the fixed wait time is four MS, up to 3 attempts;
callable<integer> task =NewCallable<integer>() {@Override PublicInteger Call ()throwsException {return2; }}; Retryer<Integer> Retryer = retryerbuilder.<integer>Newbuilder (). Retryifresult (predicates.<Integer>isNull ()). Retryifresult (Predicates.equalto (2). Retryifexceptionoftype (IOException.class). Withstopstrategy (Stopstrategies.stopafterattempt (3). Withwaitstrategy (Waitstrategies.fixedwait (300, Timeunit.milliseconds)) . build ();Try{retryer.call (Task);}Catch(executionexception e) {e.printstacktrace ();}Catch(retryexception e) {e.printstacktrace ();}
The exception is retried, each time the task execution maximum execution time is limited to 3 s, the retry interval is initially 3 s, a maximum of 1 minutes retry, with the increase of the number of retries each increment of 1 s, each retry failed, print the log;
@Override PublicInteger Call ()throwsException {return2; }}; Retryer<Integer> Retryer = retryerbuilder.<integer>Newbuilder (). Retryifexception (). Withstopstrategy (Stopstrategies.stopafterdelay (30, Timeunit.seconds)) . Withwaitstrategy (Waitstrategies.incrementingwait (3, timeunit.seconds,1, Timeunit.seconds)) . Withattempttimelimiter (attempttimelimiters.<integer>fixedtimelimit (3, Timeunit.seconds)) . Withretrylistener (NewRetrylistener () {@Override Public<V>voidOnretry (attempt<v>attempt) { if(Attempt.hasexception ()) {Attempt.getexceptioncause (). Printstacktrace (); }}). build ();Try{retryer.call (Task);}Catch(executionexception e) {e.printstacktrace ();}Catch(retryexception e) {e.printstacktrace ();}
Core Execution Logic Analysis:
LongStartTime =system.nanotime (); for(intAttemptnumber = 1;; attemptnumber++) {attempt<V>attempt; Try { //Successful ExecutionV result =Attempttimelimiter.call (callable); Attempt=NewResultattempt<v> (result, Attemptnumber, TimeUnit.NANOSECONDS.toMillis (System.nanotime ()-startTime)); } Catch(Throwable t) {//Execution failedattempt =NewExceptionattempt<v> (t, Attemptnumber, TimeUnit.NANOSECONDS.toMillis (System.nanotime ()-startTime)); } //Listener Processing for(Retrylistener listener:listeners) {listener.onretry (attempt); } //whether the termination policy is met if(!rejectionpredicate.apply (attempt)) { returnAttempt.get (); } //whether the stop policy is met if(Stopstrategy.shouldstop (attempt)) {Throw Newretryexception (Attemptnumber, attempt); } Else { //calculate the next retry interval LongSleeptime =Waitstrategy.computesleeptime (attempt); Try{blockstrategy.block (sleeptime); } Catch(interruptedexception e) {thread.currentthread (). interrupt (); Throw Newretryexception (Attemptnumber, attempt); } }}
dependency Ingestion
<Dependency> <groupId>Com.github.rholder</groupId> <Artifactid>Guava-retrying</Artifactid> <version>2.0.0</version></Dependency>
主要接口及策略介绍:
Attempt
: Perform a task at once;
AttemptTimeLimiter
: One-time task execution time limit (if a single task execution times out, the execution of the current task is terminated);
BlockStrategies
: Task blocking strategy (popularly speaking is that the current task is finished, the next task has not started this period of time to do what ...) ), the default policy is: that is, BlockStrategies.THREAD_SLEEP_STRATEGY
call Thread.sleep(sleepTime)
;
RetryException
: Retry the exception;
RetryListener
: A custom retry listener that can be used to log error logs asynchronously;
StopStrategy
: Stop retry policy, available in three types:
StopAfterDelayStrategy
: Sets a maximum allowable execution time, such as setting the maximum execution 10s, regardless of the number of times the task executes, the task terminates and returns the retry exception if the maximum time is exceeded when retrying RetryException
;
NeverStopStrategy
: Does not stop, used to need to always rotation know return expected results of the situation;
StopAfterAttemptStrategy
: Sets the maximum number of retries, stops retrying if the maximum number of retries is exceeded, and returns a retry exception;
WaitStrategy
: Wait Long policy (control interval) and return the result to the next execution time:
FixedWaitStrategy
: Fixed wait time duration strategy;
RandomWaitStrategy
: Random Wait Time duration policy (can provide a minimum and maximum time, waiting time is its interval random value)
IncrementingWaitStrategy
: Increments the Wait Time policy (provides an initial value and step, and the wait time increases with the number of retries)
ExponentialWaitStrategy
: exponential wait time strategy;
FibonacciWaitStrategy
: Fibonacci wait time duration strategy;
ExceptionWaitStrategy
: Exception duration wait policy;
CompositeWaitStrategy
: Compound time-long wait strategy;
Reference:
http://blog.csdn.net/aitangyong/article/details/53894997
1190000006918410
http://blog.csdn.net/aitangyong/article/details/53886293
Http://baijiahao.baidu.com/s?id=1575327487081031&wfr=spider&for=pc
Http://www.cnblogs.com/jianzh5/p/6651799.html
http://lintrip.com/2016/05/27/guava-retry/(the above part of the content is transferred from this article)
Spring Error Exception retry Framework Guava-retrying