我需要提供一些高保证的消息。此消息应作为有限集合(至少100个示例)传递。为了解决我的任务,我想我应该使用spring批处理。我需要为每次下一次失败的尝试配置指数增加的时间。每个数据对象最多应有5次传递尝试。我希望有机会通过db监视所有尝试和下一次重试时间。 Spring批处理为此提供了准备好的表。看来我的流程只有一个工作,但检查模式我们可以发现该工作只有状态完成状态(不是有效负载):
此外,没有尝试计算下次执行时间。
我不清楚如何配置重试周期策略。我应该使用不同的工具(如石英),还是需要深入了解弹簧批次?我不想为这个任务制作我自己的解决方案,它看起来像序数,应该有优雅的解决方案。
一旦你定义了你的工作以及如何执行它,你可以使用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次。
希望这可以帮助。