Guava Retrying
2024-09-02 16:10:27
依赖
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
使用demo
使用Guava Retrying可以简单分为三步,(1)通过RetryerBuilder工厂类构造Retryer(2)需要重试的动作实现callable接口(3)调用call方法
RetryerBuilder
@Component
public class AppRetryerBuilder {
public Retryer<Boolean> build() {
return RetryerBuilder.<Boolean>newBuilder()
//如果result为false则重试
.retryIfResult(i -> i.equals(false))
//如果执行中有异常则重试
.retryIfException()
//每次重试之间间隔三秒
.withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
//最大重试次数,当达到这个次数则抛出ExecutionException异常
.withStopStrategy(StopStrategies.stopAfterAttempt(10))
//RetryListener可以监控多次重试过程,并可以使用attempt做一些额外的事情
.withRetryListener(new RetryLogListener())
.build();
}
}
实现callable接口
Callable<Boolean> callable = () -> {
log.info("call times={}", times);
times++;
if (times == 2) {
throw new RuntimeException();
} else if (times == 3) {
throw new Exception();
} else if (times == 4) {
return false;
} else return times != 5;
};
调用
try {
Boolean call = retryer.call(callable);//也可以不用try,call方法抛出的是运行时异常
System.out.println(call);
} catch (Exception e) {
e.printStackTrace();
}
git
https://github.com/lexiaoyao1995/retry
参考
https://www.jianshu.com/p/557eb67bb3d8
最新文章
- SQL 语言 - 数据库系统原理
- JAVA 注解的几大作用及使用方法详解
- Android 实现简单音乐播放器(二)
- 【Git】笔记1
- javascript通过时区获取时间
- HTML5[7]: 实现网页版的加载更多
- ssm中使用hibernate-validator验证BO
- WPF 样式和行为
- 未能加载文件或程序集“Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad
- 64bit Ubuntu, Android AAPT, R.java
- Swift学习笔记 - 函数与闭包
- asp.net core VS goang web[修正篇]
- Visual Studio 2013进行单元测试
- Temperature hdu 3477
- Golang开发者常见的坑
- Python学习笔记 变量
- WPF 依赖属性源码 洞察微软如何实现DependencyProperty
- DDD实战进阶第一波(二):开发一般业务的大健康行业直销系统(搭建支持DDD的轻量级框架一)
- BZOJ_3626_[LNOI2014]LCA_离线+树剖
- MUI 实用教程