当前位置:网站首页>Retryer of guava
Retryer of guava
2022-07-28 07:25:00 【georgesnoopy】
Retryer The structure is relatively simple , But it is with this simple structure that a more general retry framework is implemented .

The reason why it can implement a general retry framework with a simple structure , It's good for the abstraction of trying again , So let's see what it takes to retry :
- A mechanism is needed to express the retry task .Retryer It uses Callable This interface represents a retry task . And through AttemptTimeLimiter Encapsulation implements a variety of ways to perform tasks .
- You need to decide when to try again 、 When will it come to an end? .Retryer Used Predicate This functional interface allows the user to decide when the execution is successful , When execution fails, you need to retry . And provides the following commonly used , such as :Callable Try again when the task throws an exception 、 Retry when returning the specified result and various conditional Or as well as And The combination of .
- If it doesn't work , What do I do ?Retryer adopt StopStrategy encapsulation , The number of retries is limited .
- Retry interval : One is how to specify the interval , The other is the interval , What should threads do ?Retryer Use WaitStrategy To encapsulate the retry interval 、 Use BlockStrategy To indicate what the retry interval thread should do , To extend , Then you need to rewrite Retryer#call() Method .
And you can find , These mechanisms are interface oriented ,Retryer Provides common implementations , And allow you to expand . however StopStrategy With the exception of , Only these three , Because in Retryer#call() It just realizes these three strategies .
Whole Retryer The most important one is call() Method :
public V call(Callable<V> callable) throws ExecutionException, RetryException {
long startTime = System.nanoTime();// This is for waitStrategy=StopAfterDelayStrategy Time for
for (int attemptNumber = 1; ; attemptNumber++) {//attemptNumber Is used for waitStrategy=StopAfterAttemptStrategy Number of retries
Attempt<V> attempt;
try {
V result = attemptTimeLimiter.call(callable);// AttemptTimeLimiter perform Callable Mission
attempt = new Retryer.ResultAttempt<V>(result);// Callable Result encapsulation
} catch (Throwable t) {
attempt = new Retryer.ExceptionAttempt<V>(t);
}
if (!rejectionPredicate.apply(attempt)) {// Predicate Decide whether to retry
return attempt.get();// Predicate return true It means success , Then do not try again , Return results .
}
long delaySinceFirstAttemptInMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
if (stopStrategy.shouldStop(attemptNumber, delaySinceFirstAttemptInMillis)) {// stopStrategy Decide whether to stop retrying
throw new RetryException(attemptNumber, attempt);
} else {
//waitStrategy Get retry interval .
long sleepTime = waitStrategy.computeSleepTime(attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
try {
blockStrategy.block(sleepTime);// If you want to try again , In the retry interval blockStrategy Tell the current thread what to do , The default is just a kind of , It's sleep .
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RetryException(attemptNumber, attempt);
}
}
}
}Retryer#call() The method declaration threw two exceptions :ExecutionException, RetryException , Judging from the yuan immediately, it will be thrown if it fails after reaching the number of retries RetryException, But I didn't find any statement thrown ExecutionException. Actually, I think it is Retryer A bad place , This anomaly is actually Future#get() Method declaration throws , So it's only in use attemptTimeLimiter=FixedAttemptTimeLimit When ,Callable The task is executed in a thread pool written dead inside , And then you use Future#get() Method waits for the task submitted to the thread pool to complete , And this place may throw Execution. If we don't decide attemptTimeLimiter, Default NoAttemptTimeLimiter, It won't throw out ExecutionException.
ps:AttemptTimeLimiter It's used to carry out Callable Of , But why is it called TimeLimiter? In fact, what I want to express is execution Callable Event limits for tasks :NoAttemptTimeLimiter There is no event limit , and FixedAttemptTimeLimit It's a fixed time limit , And it does Callable Time limit is to use Future#get(timeout), therefore FixedAttemptTimeLimit Internally, it is submitted to a thread pool (Executors.newCachedThreadPool()) To carry out , And then use Future#get(timeOut) To get results , In order to control Callable Purpose of execution time .
A use Retryer Of demo:
// Retry, The generic type is Callable Return value type of
Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
// stay Predicates Some static classes implement , But it doesn't include the commonly used , stay RetryerBuilder Some more are implemented in , Some common : Exception retry 、 Return the specified value and try again
// ps:RetryerBuilder It only realizes a variety of conditions or( Will be multiple Predicate Put it in the list , Traverse when calling , There is a return true Just go back to true, similar or The effect of )
// Predicates Realized or as well as and, Choose according to the specific situation , Or realize one by yourself . Actually RetryerBuilder Can meet the vast majority of needs .
.retryIfException()// Predicate<Attempt<String>> Decide what failure is , retry .
.retryIfResult(new Predicate<String>() {
@Override
public boolean apply(@Nullable String input) {
return input.equals("aaa");
}
})// The relationship between these two is or : The actual task throws an exception , Or the return value is aaaa, Will try again . If it is not set, it is always successful , It doesn't try again .
.withStopStrategy(StopStrategies.stopAfterAttempt(3))// Retry end limit . No setting is NeverStopStrategy, Infinite retries
.withWaitStrategy(WaitStrategies.fixedWait(200, TimeUnit.MICROSECONDS))// Retry interval . Do not set default FixedWaitStrategy(0), In fact, it doesn't sleep
//.withAttemptTimeLimiter(AttemptTimeLimiters.fixedTimeLimit(1,TimeUnit.SECONDS)) // No setting is AttemptTimeLimiters
//.withAttemptTimeLimiter(new KAttemptTimeLimiter(3))
//.withBlockStrategy(BlockStrategies.threadSleepStrategy()) // No setting is ThreadSleepStrategy( Thread to sleep )
.build();
// The actual use
try {
String result = retryer.call(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println(" I'm trying again ...");
//System.out.println(Thread.currentThread().getId() + " " + Thread.currentThread().getName());
throw new RuntimeException("a");
//return "aaa";
}
});
System.out.println(result);
// This is FixedAttemptTimeLimit Will be thrown , stay feature.get() Abnormal throwing , And retry cannot be an exception thrown retry , Otherwise, you can't come here , Because when there is an exception, try again first , Then try again. What Chen Gong throws is RetryException
}catch (ExecutionException e ){
System.out.println("ExecutionException:"+e);
}catch (RetryException e){
System.out.println("RetryException:"+e);
}
边栏推荐
- 5g commercial third year: driverless "going up the mountain" and "going to the sea"
- ELK日志分析系统的部署
- Earliest deadline first (EDF)
- 【jvm优化超详细】常见的JVM调优场景
- Nrf51822 review summary
- uniapp 移动端 两种横竖屏切换方案
- Addition, deletion, check and modification of sequence table
- 大话持久性与redolog
- Freemaker merges cells, uses if and else tags, and processes null and empty strings
- Soft exam certificate can be used like this! Get a certificate = get a professional title?
猜你喜欢
随机推荐
Pytorch - storage and loading model
Install Nessus under win
Tailing microelectronics B91 general development board integrated into the trunk of openharmony community
Qucs preliminary use guide (not Multism)
Shell--- circular statement practice
删除链表中的节点——每日一题
How to understand CMS collector to reduce GC pause time
Easypoi one to many, merge cells, and adapt the row height according to the content
Metasploit penetration MS7_ 010 exercise
【jvm优化超详细】常见的JVM调优场景
build_ opencv.sh
Date n days ago
How low-end computers learn secrets in depth - using the mistgpu computing platform
object detection
nodejs操作MongoDB
C language maze
浅谈深分页问题
Image segmentation method
High response ratio first
Basic knowledge of video format: let you know MKV, MP4, h.265, bit rate, color depth, etc








