guava-retry使用笔记
xml依赖
xml
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
使用案例
重试3次,每次间隔3秒
java
/**
* 重试3次,每次间隔3秒
*/
@Test
void testGuavaRetry(){
//定义请求实现
Callable<Boolean> callable = ()->{
//do something...
log.info("call task... ...");
throw new RuntimeException();
};
//定义重试机制
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
//重试条件
.retryIfResult(Objects::isNull)
//异常重试源
.retryIfExceptionOfType(IOException.class)
.retryIfRuntimeException()
.retryIfResult(res->res=false)
//等待间隔时间
.withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
//设置最大重试次数
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
try {
retryer.call(callable);
}catch (RetryException | ExecutionException e){
e.printStackTrace();
}
}
以指数递增的间隔等待重试
java
@Test
void testGuavaRetry2(){
Callable<Boolean> callable = ()->{
//do something...
log.info("call task... ...");
throw new RuntimeException();
};
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfExceptionOfType(IOException.class)
.retryIfRuntimeException()
//以指数递增的间隔等待,直到最多5分钟,5分钟后,每隔5分钟重试1次
.withWaitStrategy(WaitStrategies
.exponentialWait(100,5,TimeUnit.MINUTES))
//设置永远重试
.withStopStrategy(StopStrategies.neverStop())
.build();
try {
retryer.call(callable);
}catch (RetryException | ExecutionException e){
e.printStackTrace();
}
}
失败后重试,按斐波那契回退间隔重试
java
@Test
void testGuavaRetry3(){
Callable<Boolean> callable = ()->{
//do something...
log.info("call task... ...");
throw new RuntimeException();
};
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfExceptionOfType(IOException.class)
.retryIfRuntimeException()
//失败后重试,按斐波那契回退间隔,直到2分钟,2分钟后,每隔2分钟重试1次
.withWaitStrategy(WaitStrategies
.fibonacciWait(100,2,TimeUnit.MINUTES))
//设置永远重试
.withStopStrategy(StopStrategies.neverStop())
.build();
try {
retryer.call(callable);
}catch (RetryException | ExecutionException e){
e.printStackTrace();
}
}