Guava Retry重试机制
1、添加pom依赖
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
2、Guava Retry具体使用
public void guavaRetry(String param) {
Retryer<Boolean> retry = RetryerBuilder.<Boolean>newBuilder()
.retryIfResult(Predicates.equalTo(false))//设置根据结果重试
.retryIfException()//设置异常重试源
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))//设置等待间隔时间(失败后,将等待固定的时长进行重试)
.withStopStrategy(StopStrategies.stopAfterAttempt(5))// 重试停止策略:设置最大重试次数
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
System.out.println("准备开始第几次重试:"+attempt.getAttemptNumber());
System.out.println("是异常导致的重试还是正常返回:"+attempt.hasException());
System.out.println("如果是异常导致的重试,那么获取具体具体的异常类型:"+attempt.getExceptionCause());
}
})
.build();
AtomicReference<String> message = new AtomicReference<>("");
try {
retry.call(()->{
System.out.println("尝试");
String method = this.method();//该方法出现异常后,后面代码不会继续执行
if (!"成功".equals(method)) {
message.set("失败");
}else {
message.set("");
}
return true;
});
} catch (Exception e) {
message.set("失败");//整个尝试失败
e.printStackTrace();
}finally {
//尝试一定次数后的最终处理
System.out.println(message.get()+"++++++++++");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏