簡體   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