【发布时间】:2019-05-08 16:41:02
【问题描述】:
我最近开始学习 Spring Batch 并为一个项目做 POC,我卡在重试策略和跳过策略上。我对这些问题的解决方案有点模棱两可
问题1):我们可以对一个实例同时使用SkipPolicy和Retry Policy吗,读者有一个例外,现在框架将寻找我们定义的策略。它会同时适用于政策还是我们首先定义的政策..? (我已经在我的 POC 中实现了这一点,但它只会跳过策略而不是重试策略) 我要检查的是,如果异常是 Skippable 的实例,那么如果异常是 Retryable 的实例,则执行我的业务逻辑,然后重试一定的限制。
问题 2):如何获取失败记录的数据,我知道有侦听器(ReadListener、WriteListener、ProcessListener)但是,如果重试超过限制,我想记录导致该异常的记录。
问题 3):在将批处理写入数据库或将其写入某个位置(CSV 或平面文件)时,我们有什么方法可以获得准确的失败记录
我确实尝试过这些场景,但无法清楚地理解这一点。
任何帮助将不胜感激:)
这是步骤配置
@Bean
public Step step() {
return stepBuilderFactory.get("eventStep")
.<Employee, Employee>chunk(3)
.reader(employeeItemReader())
.listener(stepItemReadListener)
.listener(noWorkFoundStepExecutionListener)
.listener(new StepItemReadListener())
.processor(processor())
.writer(writer())
.faultTolerant()
.skipPolicy(dbConnectivitySkipper)
.retryPolicy(stepRetry)
.listener(stepItemWriteListner)
.build();
}
跳过政策的实施
@Override
public boolean shouldSkip(Throwable exception, int skipCount) throws SkipLimitExceededException {
if (exception instanceof DuplicateKeyException && skipCount <= 5) {
return true;
} else if (exception instanceof NumberFormatException && skipCount <= 5){
return true;
} else {
return false;
}
重试策略的实施
public boolean canRetry(RetryContext context) {
Throwable t = context.getLastThrowable();
if (t instanceof NullPointerException && context.getRetryCount() <= maxAttempts) {
return true;
} else if (t instanceof StepListenerFailedException && context.getRetryCount() <= maxAttempts){
return true;
} else {
return false;
}
}
【问题讨论】:
标签: java spring-batch