微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我们如何在RetryContext中获得JobId?

如何解决我们如何在RetryContext中获得JobId?

我只是在这里扩展我的问题-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";
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。