当前位置:网站首页>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);
}
边栏推荐
- 软考证书还能这样用!拿到证书=获得职称?
- Basic knowledge of video format: let you know MKV, MP4, h.265, bit rate, color depth, etc
- nodejs操作MongoDB
- JS secondary linkage Department
- VCF file production
- How did tensor leak your memory / video memory
- MHA高可用配置及故障切换
- NoSQL之Redis配置与优化
- Review of C language (byte alignment)
- Redis主从复制原理及配置
猜你喜欢
随机推荐
Gd32f407 porting freertos+lwip
How did tensor leak your memory / video memory
Review of C language (byte alignment)
CAS vs 数据库乐观锁
nodejs操作MongoDB
Standard C language learning summary 9
WiFi one click connection configuration of raspberry pie
Method of decomposing path into directory name and file name
C语言详解系列——数组详解,一维数组、二维数组
Continous Gesture Recognition with hand-orented spatiotemporal feature
Current limiting ratelimiter of guava
Not used for the longest time recently
Log in to heroku and the solution of IP address mismatch appears
[a little knowledge] AQS
VCF file production
MySQL queries all descendant nodes under the parent node. When querying the user list, it is processed by multi-level (company) departments. According to reflection, it recurses the tree structure too
Nrf51822 review summary
Circular linked list problem
Shortest seek time first (SSTF)
再次出现用户净流失,大失颜面的中国移动推出超低价套餐争取用户









