新增操作 失败后重试

在我从事的每个项目中,始终需要某些功能:重试操作。 通常,这是关于通过网络的呼叫,该呼叫可能一次失败,但随后会成功。 它可能涉及许多其他内容,主要包括与另一个系统的通信(无论是否通过网络)。 它的功能,你绝对需要在大多数应用中,特别是如果你想他们是高可用性( 如这里指出的 ,例如)。

每次我必须在项目中引入此功能时,我都会检查我们已导入的标准库,没有这样的东西。 因此,我总是最终将我以前的项目中的同一段代码复制粘贴。 我什至不记得我是什么时候第一次介绍它的,但是从那以后我就在“旅行”。 所以这里是:

/*** Class that provides retrying functionality. Example:* <p></p>* <code>* Callable<String> callable = new Callable<String>() {..};* String result = RetryableOperation.create(callable).retry(5, IOException.class);* </code>** @param <T> the return type of the operation*/
public class RetryableOperation<T> {private Callable<T> callable;private Runnable runnable;private boolean exponentialBackoff;private int backoffInterval = 500;/*** Create a retryable operation based on a Callable instance. The return* type of retry(..) is the type parameter of the Callable instance.** @param callable* @return*      a new instance of RetryableOperation*/public static <T> RetryableOperation<T> create(Callable<T> callable) {return new RetryableOperation<T>().withCallable(callable);}/*** Creates a retryable operation based on a Runnable instance. In this case* the retry(..) method always returns null.** @param runnable* @return*      a new instance of RetryableOperation*/public static RetryableOperation<?> create(Runnable runnable) {return new RetryableOperation<Object>().withRunnable(runnable);}/*** Retries the operation. Retrying happens regardless of the exception thrown.** @param retries*      number of retries before the exception is thrown to the caller* @param exceptions*      the operation will be retried only if the exception that occurs is one of the*      exceptions passed in this array* @return*      the result of the operation (null if Runnable is used instead of Callable)* @throws Exception*      the exception that occurred on the last attempt*/public T retry(int retries, Class<? extends Exception>... exceptions) throws Exception {if (callable == null && runnable == null) {throw new IllegalStateException("Either runnable or callable must be set");}Set<Class<? extends Exception>> retryFor = new HashSet<Class<? extends Exception>>();retryFor.addAll(Arrays.asList(exceptions));for (int i = 0; i < retries; i++) {try {if (exponentialBackoff && i > 0) {int sleepTime = (int) ((Math.pow(2, i) - 1) / 2) * backoffInterval;Thread.sleep(sleepTime);}if (callable != null) {return callable.call();} else if (runnable != null) {runnable.run();return null;}} catch (Exception e) {if (retryFor.isEmpty() || retryFor.contains(e.getClass())) {if (i == retries - 1) {throw e;}} else {// if the exception is not the expected one, throw it immediatelythrow e;}}}// can't be reached - in case of failure on the last iteration the exception is rethrownreturn null;}private RetryableOperation<T> withCallable(Callable<T> callable) {this.callable = callable;return this;}private RetryableOperation<T> withRunnable(Runnable runnable) {this.runnable = runnable;return this;}public RetryableOperation<T> withExponentialBackoff() {this.exponentialBackoff = true;return this;}
}
1

这很简单,但是效果很好。 您可以重试每个失败,也可以重试特定的异常(您不想重试NullPointerException,但是必须配置适当的超时,然后重试网络故障):

Result result = op.retry(3);...Result result = op.retry(3, IOException.class);

我什至曾建议番石榴将其包含在内,然后再看其他类似的提案,但据我所知,番石榴或apache commons中都没有这种功能。 而且我不会创建一个新的github项目,因为那将需要在maven Central中管理一个条目,而对于单个实用程序类来说,这是一项很大的工作。

当然,还有其他解决方法,它们具有更大的API和占用空间- 重试番石榴扩展和最近提取为单独的项目spring-retry 。 它们值得检查,并且具有要导入的Maven依赖项。

无论选择什么选项,请检查它是否支持匿名功能(自Java 8起)。 它可能会自动执行,但仍会检查。

关键是要通过一个非常简单的API来提供此功能,以便您可以避免用户可避免的故障-必须重试几次对外部系统的调用。

翻译自: https://www.javacodegeeks.com/2015/10/retryable-operations.html

新增操作 失败后重试

新增操作 失败后重试_可重试的操作相关推荐

  1. 异步重试_异步重试模式

    异步重试 当您有一段经常失败且必须重试的代码时,此Java 7/8库提供了丰富且简洁的API以及针对此问题的快速且可扩展的解决方案: ScheduledExecutorService schedule ...

  2. kafka消息处理失败后如何处理_面试题:Kafka 会不会丢消息?怎么处理的?

    Kafka存在丢消息的问题,消息丢失会发生在Broker,Producer和Consumer三种. Broker Broker丢失消息是由于Kafka本身的原因造成的,kafka为了得到更高的性能和吞 ...

  3. IDEA提交项目代码到码云失败后的回滚重提交操作

  4. java 操作excel的类_探究下Java操作Excel的几类工具

    引言 java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI ...

  5. python操作ppt的模块_详解 Python 操作 PPT 的各种骚操作!

    1.python-pptx模块简介 使用python操作PPT,需要使用的模块就是python-pptx,下面来对该模块做一个简单的介绍. 这里提前做一个说明:python操作PPT,最好是我们提前设 ...

  6. 【Spring Cloud】OpenFeign和Spring Cloud Loadbalancer调用失败后的重试机制比较

    1 概述 搭建一个微服务系统,有两个服务,Client和Server,Server有三个实例A.B.C,我让Client调用Server,Loadbalancer负载分担默认采用轮询机制,当Serve ...

  7. mysql heartbeat 慢_当master down掉后,pt-heartbeat不停重试会导致内存缓慢增长_mysql

    当master down掉后,pt-heartbeat不断重试会导致内存缓慢增长 最近同事反映,在使用pt-heartbeat监控主从复制延迟的过程中,如果master down掉了,则pt-hear ...

  8. 操作失败,请稍后重试

    文章目录 操作失败,请稍后重试 原因:C盘EXAM文件夹无法删除,使用360强制删除. 步骤: 1.退出考试,双击鼠标左键,打开"此电脑"或"我的电脑" 2.双 ...

  9. 第三期:gRPC客户端与服务端连接失败后,是否会有重试机制?

    grpc 版本1.50 client.go 代码: func main() { flag.Parse() // Set up a connection to the server. conn, err ...

最新文章

  1. 为保障处理器平稳运行请“三知”cpu
  2. Windows服务异常自动关闭
  3. 网络安全-XSS笔记
  4. 来场产品设计师的对决吧!MacBook、大疆OSMO等你拿
  5. tensorflow随笔-constant
  6. 基于Xml 的IOC 容器-分配解析策略
  7. VMware安装CentOS之二——最小化安装CentOS
  8. 我想做个MP3,要怎么入手?
  9. 拼装机器人感想_智能机器人心得体会
  10. fastdfs-配置存储服务器storage
  11. Matrix Factorization: A Simple Tutorial and Implementation in Python
  12. 程序员告诉你如何用技术手段玩转冲顶大会
  13. java类注解是否可以通过实现接口或继承父类的方式获得
  14. c# socket操作智嵌物联的网络继电器板
  15. Win7安装VMware Tools问题
  16. 成长路线 - Android移动开发架构师
  17. 使用WebSocket实现多组即时对战五子棋
  18. css背景图片高斯模糊_CSS3 filter(滤镜) 制作图片高斯模糊无需JS
  19. 简历中的工作经历要怎么写?
  20. awk 分隔符_awk 命令快速入门

热门文章

  1. P6805-[CEOI2020]春季大扫除【贪心,树链剖分,线段树】
  2. P4071-[SDOI2016]排列计数【组合计数,错排】
  3. 欢乐纪中某A组赛【2019.1.19】
  4. jzoj1264,P2866-乱头发节,糟糕的一天Bad Hair Day【单调栈】
  5. 【2018.3.24】模拟赛之二-ssl2546 求和【贪心】
  6. 【LCT】旅游(P1505)
  7. 【模拟】表达式求值(jzoj 1768)
  8. P3157 动态逆序对 ,树状数组套动态开点线段树
  9. Memcached总结
  10. MySQL extract()函数