[英]A retry mechanism in java with ScheduledExecutorService
I am trying to write a retry mechanism in java, that reties a function after 3 minutes in case of failure, and retries up to maximum 3 times.我正在尝试在 java 中编写一个重试机制,在失败的情况下 3 分钟后重新连接一个 function,最多重试 3 次。 I do not want to use Thread.Sleep, and instead I was thinking about using ScheduledExecutorService.
我不想使用 Thread.Sleep,而是考虑使用 ScheduledExecutorService。 I am trying to figure out what would be a good implementation for it.
我试图弄清楚什么是一个好的实现。 It seems executor.schedule() does not the runnable inside the runnable.
似乎 executor.schedule() 不是可运行对象中的可运行对象。
I was thinking something like this:我在想这样的事情:
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);
I would suggest you use the spring-retry library instead of writing your own implementation.我建议您使用 spring-retry 库而不是编写自己的实现。
Create a RetryTemplate instance.创建一个 RetryTemplate 实例。 Sample code here - https://github.com/innovationchef/batchpay/blob/master/src/main/java/com/innovationchef/service/PayApiRetryTemplate.java
此处的示例代码 - https://github.com/innovationchef/batchpay/blob/master/src/main/java/com/innovationchef/service/PayApiRetryTemplate.java
Then call you method like this -然后像这样调用你的方法 -
retryTemplate.execute(arg -> callMyFunction());
This code seems to work, and resolves the issue I had.此代码似乎有效,并解决了我遇到的问题。 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:
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);
Any idea how to fix that?知道如何解决吗?
Here is the entire code:这是整个代码:
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");
}
Thanks @Turing85 for the help and useful comments.感谢@Turing85 的帮助和有用的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.