问题描述
我只是在这里扩展我的问题-Spring Retry doesn't works when we use RetryTemplate?。
我们如何在JobId
中获得RetryContext
?
我通过链接Spring Batch how to configure retry period for failed jobs,但仍然不知道。
@Component
@Slf4j
public class RecoveryCallback implements RecoveryCallback<String>{
@Autowired
private NamedParameterJdbcTemplate namedJdbcTemplate;
@Autowired
private AbcService abcService;
@Value("#{stepExecution.jobExecution.jobId}")
private Long jobId;
@Override
public String recover(RetryContext context) throws Exception {
log.warn("RecoveryCallback | recover is executed ...");
ErrorLog errorLog = ErrorLog.builder()
.jobName("ABC")
.stepName("RETRY_STEP")
.stepType("RETRY")
....
....
....
.jobId(jobId)
.build();
abcService.updateErrLog(errorLog);
return "Batch Job Retried and exausted with all attemps";
}
}
解决方法
由于要在Spring bean的字段中注入stepExecution.jobExecution.jobId
,因此需要使此bean Step
成为作用域。通过这种方法,不使用RetryContext。
如果要使用重试上下文,则需要先将jobId放在可重试方法的上下文中。根据您的链接问题:
retryTemplate.execute(retryContext -> {
JobExecution jobExecution = jobLauncher.run(sampleAcctJob,pdfParams);
if(!jobExecution.getAllFailureExceptions().isEmpty()) {
log.error("============== sampleAcctJob Job failed,retrying.... ================");
throw jobExecution.getAllFailureExceptions().iterator().next();
}
logDetails(jobExecution);
// PUT JOB ID in retryContext
retryContext.setAttribute("jobId",jobExecution.getExecutionId());
return jobExecution;
});
这样,您可以在recover
方法中从上下文中获取jobId:
@Override
public String recover(RetryContext context) throws Exception {
log.warn("RecoveryCallback | recover is executed ...");
ErrorLog errorLog = ErrorLog.builder()
.jobName("ABC")
.stepName("RETRY_STEP")
.stepType("RETRY")
....
....
.jobId(context.getAttribute("jobId"))
.build();
abcService.updateErrLog(errorLog);
return "Batch Job Retried and exausted with all attemps";
}