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()+"++++++++++");
}
}
posted @   懂得归零  阅读(108)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示