繁体   English   中英

java 中带有 ScheduledExecutorService 的重试机制

[英]A retry mechanism in java with ScheduledExecutorService

我正在尝试在 java 中编写一个重试机制,在失败的情况下 3 分钟后重新连接一个 function,最多重试 3 次。 我不想使用 Thread.Sleep,而是考虑使用 ScheduledExecutorService。 我试图弄清楚什么是一个好的实现。 似乎 executor.schedule() 不是可运行对象中的可运行对象。

我在想这样的事情:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final int count = 1;
final int MAX_RETRY = 3;
Runnable runnable = () -> {
   try {
     //This function can fail and throw FunctionException
     callMyFunction();
   }
   catch (FunctionException e) {
     if (++count <= MAX_RETRY) {
        executor.schedule(runnable, 30*60*1000);
     }
   }
};

executor.execute(runnable);

我建议您使用 spring-retry 库而不是编写自己的实现。

创建一个 RetryTemplate 实例。 此处的示例代码 - https://github.com/innovationchef/batchpay/blob/master/src/main/java/com/innovationchef/service/PayApiRetryTemplate.java

然后像这样调用你的方法 -

retryTemplate.execute(arg -> callMyFunction());

此代码似乎有效,并解决了我遇到的问题。 I could not use lambda to implement my Runnable function, as in lambda there is no way to have "this" reference the instance created by a lambda expression in this line:

scheduler.schedule(this, 1, TimeUnit.SECONDS);

知道如何解决吗?

这是整个代码:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
AtomicInteger counter = new AtomicInteger(1);
final int MAX_RETRY = 3;
scheduler.execute(new Runnable() {
   @Override
   public void run () {
   try {
     System.out.println("Attempt number: " + counter.get());
     functionCall();
     scheduler.shutdown();
   }
   catch (Exception e) {
      if (counter.get() < MAX_RETRY) {
            System.out.println("Attempt number: " + counter.getAndIncrement() + " failed.");
            scheduler.schedule(this, 1, TimeUnit.SECONDS);
      }
      else {
         System.out.println("Error message: " + e.getMessage());
         scheduler.shutdown();
      }
   }
 }
 });
 }
    
 public static void functionCall() {
     throw new RuntimeException("Does not work");
 }

感谢@Turing85 的帮助和有用的评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM