重试任务框架

Scr*_*ers 25 java

我有很多情况需要在失败的情况下重试任务n次(有时使用某种形式的重试前退避逻辑).通常,如果抛出异常,则应重试该任务以达到最大重试次数.

我可以很容易地写一些东西来做这个相当一般,但不想重新发明轮子我想知道是否有人可以推荐任何框架.我唯一能找到的是:Ant Retry但我不想直接在我的应用程序中使用Ant任务.

谢谢

dog*_*ane 16

您可以RetriableTasks按照本文中的概述使用:在Java中重试操作.如果您愿意,可以很容易地更改其等待算法.

示例代码:

//creates a task which will retry 3 times with an interval of 5 seconds
RetriableTask r = new RetriableTask(3, 5000, new Callable(){
    public Object call() throws Exception{
        //put your code here
    }
});
r.call();
Run Code Online (Sandbox Code Playgroud)


Jon*_*han 14

查看故障保险.它是一个简单的零依赖库,用于执行重试,支持同步和异步重试,Java 8集成,事件监听器,与其他异步API的集成等:

RetryPolicy retryPolicy = new RetryPolicy()
  .handle(ConnectException.class, SocketException.class);
  .withMaxRetries(3);

Connection connection = Failsafe.with(retryPolicy).get(() -> connect());
Run Code Online (Sandbox Code Playgroud)

不容易.


mul*_*lya 9

如果你使用Spring:

//import the necessary classes
import org.springframework.batch.retry.RetryCallback;
import org.springframework.batch.retry.RetryContext;
import org.springframework.batch.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.batch.retry.policy.SimpleRetryPolicy;
import org.springframework.batch.retry.support.RetryTemplate;
...

// create the retry template
final RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new SimpleRetryPolicy(5));
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(1000L);
template.setBackOffPolicy(backOffPolicy);

// execute the operation using the retry template
template.execute(new RetryCallback<Remote>() {
  @Override
  public Remote doWithRetry(final RetryContext context) throws Exception {
    return (Remote) Naming.lookup("rmi://somehost:2106/MyApp");
  }
});
Run Code Online (Sandbox Code Playgroud)

原创博文

  • 更具体地说,如果您使用Spring Batch并希望依赖Spring Batch. (2认同)

Sun*_*amy 5

如果您使用的是Spring,那么使用Spring Retry Library 非常简单

现在,Spring Retry是一个单独的库(之前Spring Batch的一部分)框架。

步骤1:添加spring retry依赖项。

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.1.2.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

步骤2:@EnableRetry在您的类中添加注释,该注释包含应用程序的main()方法任何类中的注释@Configuration

步骤3:@Retryable在您的方法中添加注释,以防万一,请重试/调用。

@Retryable(maxAttempts=5,backoff = @Backoff(delay = 3000))
public void retrySomething() throws Exception{
    logger.info("printSomething{} is called");
    throw new SQLException();
}
Run Code Online (Sandbox Code Playgroud)

@Retryable注释将重试/调用retrySomething()5次(包括第一次失败)。

当前线程将在下一次重试之间等待3000毫秒或3秒