Spring Batch如何配置失败作业的重试周期 [英] Spring Batch how to configure retry period for failed jobs
本文介绍了Spring Batch如何配置失败作业的重试周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要投递一些高保证金的消息。 此消息应作为有限的集合(至少作为示例100条)交付。 为了解决我的任务,我想我应该使用Spring Batch。 我需要为每次失败的尝试配置成倍增加的时间。 每个数据对象最多应该有5次传送尝试。 我希望有机会通过数据库监控所有尝试和下一次重试时间。 Spring Batch为此提供了准备好的表格。 我的流似乎只有一个作业,但是检查架构可以发现,作业只有状态完成状态(不是有效负载):
此外,既没有尝试次数,也没有下次执行时间。
问题:
我不清楚如何配置重试周期策略。 我应该使用不同的工具(如石英),还是需要更深入地研究春季批次?我不想为这项任务自己做解决方案,它看起来像是有序的,应该有一个优雅的解决方案。
推荐答案
定义作业及其执行方式后,可以使用Spring Retry,它提供了开箱即用的ExponentialBackOffPolicy
。下面是一个示例:
import java.time.LocalDateTime;
import org.junit.Test;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
public class RetryTemplateTest {
private Job job; // under test, has to be initialized
@Test
public void testExponentialBackoff() throws Exception {
// configure backoff policy
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
exponentialBackOffPolicy.setInitialInterval(1000);
exponentialBackOffPolicy.setMultiplier(2.0);
exponentialBackOffPolicy.setMaxInterval(10000);
// configure retry policy
SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(5);
// configure retry template
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
retryTemplate.setRetryPolicy(simpleRetryPolicy);
// run the job with retry on failure
retryTemplate.execute(new RetryCallback<JobExecution, Exception>() {
@Override
public JobExecution doWithRetry(RetryContext context) throws Exception {
return run(job);
}
});
}
private JobExecution run(Job job) throws Exception {
System.out.println(LocalDateTime.now() + ": running job");
if (true) { // just for test
throw new Exception("Job failed");
}
return null;
}
}
此示例打印:
2019-03-13T09:19:21.882: running job
2019-03-13T09:19:22.892: running job
2019-03-13T09:19:24.893: running job
2019-03-13T09:19:28.894: running job
2019-03-13T09:19:36.895: running job
java.lang.Exception: Job failed
如您所见,重试模板在21秒、22秒、24秒、28秒和36秒启动了该作业,并且在失败之前最多重试了5次。
希望这对您有帮助。
这篇关于Spring Batch如何配置失败作业的重试周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文