首页 > 解决方案 > 我们如何在 RetryContext 中获取 JobId?

问题描述

我只是在这里扩展我的这个问题 -当我们使用 RetryTemplate 时 Spring Retry 不起作用?.

我们怎样才能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";
    }
}

标签: springspring-batchspring-retry

解决方案


由于您正在注入stepExecution.jobExecution.jobIdSpring bean 的字段,因此您需要将此 bean 设置为Step作用域。使用这种方法,不使用 RetryContext。

如果要使用重试上下文,则需要先将jobId放入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;
    });

这样,您可以从方法中的上下文中获取 jobId recover

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

推荐阅读