当前位置: 首页 > news >正文

Java 开源重试类 guava-retrying 使用案例

使用背景

需要重复尝试执行某些动作,guava-retrying 提供了成型的重试框架

依赖

        <dependency><groupId>com.github.rholder</groupId><artifactId>guava-retrying</artifactId><version>${retrying.version}</version><exclusions><exclusion><groupId>com.google.guava</groupId><artifactId>guava</artifactId></exclusion></exclusions></dependency>

${retrying.version} 实际为 2.0.0

如果已有 guava 缓存框架引入则可以像上面一样去除,否则可以保留

定义工具类

import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.RetryListener;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.StopStrategy;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.base.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.StopWatch;import java.text.MessageFormat;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;@Slf4j
public class RetryUtil {private RetryUtil(){}/*** 根据输入的condition重复做task,在规定的次数内达到condition则返回,* 如果超过retryTimes则返回null, 重试次数,整个重试时间以及retry exception都会记录log* 需要注意调用的时候需要新起一个线程,不然重试失败会阻塞当前线程** @param condition  重试条件,比如接口返回errorCode为处理中,或不是最终需要的结果* @param task       重试做的任务* @param sleepTime  重试间隔时间,单位毫秒* @param retryTimes 最大重试次数* @return targetBean*/public static <V> Optional<V> retry(Predicate<V> condition, Callable<V> task, int sleepTime, Integer retryTimes) {Optional<V> result = Optional.empty();StopStrategy stopStrategy = null;if (retryTimes == null) {stopStrategy = StopStrategies.neverStop();} else {stopStrategy = StopStrategies.stopAfterAttempt(retryTimes);}StopWatch stopWatch = new StopWatch();try {stopWatch.start();Retryer<V> retry = RetryerBuilder.<V>newBuilder()// 默认任务执行过程中发生异常自动重试.retryIfException()// 重试条件(按照业务场景).retryIfResult(condition)// 等待策略.withWaitStrategy(WaitStrategies.fixedWait(sleepTime, TimeUnit.MILLISECONDS))// 重试策略.withStopStrategy(stopStrategy)// 重试监听器.withRetryListener(new RetryListener() {@Overridepublic <V> void onRetry(Attempt<V> attempt) {// 记录重试次数和异常信息log.info(MessageFormat.format("{0}th retry", attempt.getAttemptNumber()));if (attempt.hasException()) {log.error(MessageFormat.format("retry exception:{0}", attempt.getExceptionCause()));}}}).build();// 开始执行重试任务result = Optional.ofNullable(retry.call(task));} catch (Exception e) {log.error("retry fail:", e);} finally {stopWatch.stop();log.info("retry execute time" + stopWatch.getTime());}return result;}
}

实际使用

    private void xxxxXxxxx() {Predicate<Boolean> condition = result -> result;RetryUtil.retry(condition::test,() -> xxxxxxService.xxxxXxxx(),60000,60);}

其中 xxxxxxService.xxxxXxxx() : 方法为要重试的内容,同时改方法要返回
在这里插入图片描述
条件的指定类型。

第一个为入参为重试条件。

60000 代表重试时间间隔,单位 毫秒

60 标识重试次数

http://www.lryc.cn/news/239103.html

相关文章:

  • 服务器 jupyter 文件名乱码问题
  • Ubuntu设设置默认外放和麦克风设备
  • 【教程】Sqlite迁移到mysql(django)
  • 【漏洞复现】DPTech VPN存在任意文件读取漏洞
  • CentOS 8搭建WordPress
  • 服务器安全防护导致使用多款行业顶尖软件搭配使用,还是单独一款解决呢?
  • 【Spring篇】Spring注解式开发
  • 14.(vue3.x+vite)组件间通信方式之pinia
  • DolphinDB 浙商银行 | 第二期现场培训圆满结束
  • DBS note4:Buffer Management
  • Linux 中 .tar 和 tar.gz 的区别
  • 区域人员超限AI算法的介绍及TSINGSEE视频智能分析技术的行业应用
  • asp.net mvc点餐系统餐厅管理系统
  • SpringBoot 使用多SqlSessionFactory下的事务问题
  • 浏览器内置NoSQL数据库IndexedDB
  • 网络参考模型与标准协议(二)-TCP/IP对等模型详细介绍
  • 万宾科技智能井盖传感器,预防城市道路安全
  • GCC/Make/CMake 工具链
  • GO抽象工厂模式
  • Linux 磁盘/分区/修复 命令
  • php一句话木马免杀
  • 深度学习人体跌倒检测 -yolo 机器视觉 opencv python 计算机竞赛
  • 轻松整理文件夹,将视频文件全部归类到另一个文件夹!
  • 存储服务器特征是什么
  • Conditional GAN
  • OOM问题排查+Jvm优化
  • 链表:C++实现
  • 使用JMX监控ZooKeeper和Kafka
  • 蓝桥等考C++组别七级008
  • sam和mobilesam导出预处理的onnx