我们如何获取 RetryContext 中的 JobId?

How can we get the JobId in the RetryContext?

我只是在这里扩展我的这个问题 -

我们怎样才能在RetryContext中得到JobId

我经历了link: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。

如果要使用retry context,那么需要先将jobId放到context中的retryable方法中。来自您的链接问题:

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";
}