且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在spring批处理应用程序中设置退出状态

更新时间:2023-01-09 22:40:59

我有一个类似的问题,并在5分钟前解决了。
我有多个步骤做'stuff'和默认的失败步骤,当所有其他步骤抛出异常时调用。

I had a similar issue and just solved it 5 minutes ago. I have multiple steps doing 'stuff' and a default "failure step" that is called when all other steps throw an exception.

抛出一个步骤异常将被放弃在'spring-batch'逻辑中,但我需要它们失败才能重新启动它们。
因此,在尝试使用侦听器和强制状态后,我终于通过在调用失败步骤之后更新已放弃的步骤来使其工作。

The steps that throw an exception will be Abandoned in 'spring-batch' logic, but I need them to be Failed so that I can restart them. So, after trying with listeners and forcing statuses, I finally got it to work by updating the abandoned step(s) after the 'failure step' is called.

所以我的'失败步骤'将如下所示:

So my 'failure-step' will look like this :

public class EnleveDossiersRejetesEtMAJSteps implements Tasklet {

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    /**some business logic code for my step, AND the code bellow*/

    if (chunkContext.getStepContext() != null && chunkContext.getStepContext().getStepExecution() != null) {
        Long jobExecutionId = chunkContext.getStepContext().getStepExecution().getJobExecutionId();

        batchTablesService.updateJobStepStatuses(jobExecutionId, BatchStatus.ABANDONED, BatchStatus.FAILED);
    }

    /** end the step like expected */
    return RepeatStatus.FINISHED;
    }
}

我的'batchTablesService'是我创建的服务类,链接到简单检索所有步骤的DAO,然后对于所有放弃步骤,它将它们更新为失败。
如下所示:

My 'batchTablesService' is a Service class that I created, which links to a DAO that simply retrieves all steps, then for all 'Abandoned' steps, it updates them to 'Failed'. Like so :

@Override
public void updateJobStepStatuses(Long jobExecutionId, BatchStatus sInitial, BatchStatus sFinal) {
    log.debug("-- call updateJobStepStatuses(" + jobExecutionId + "," + sInitial + "," + sFinal + ")");

    List<BatchStepExecution> steps = getStepExecutions((int) (long) jobExecutionId, null);
    for (BatchStepExecution step : steps) {
        if (!step.getStatus().isEmpty() && step.getStatus().equalsIgnoreCase(sInitial.toString())) {
            step.setStatus(sFinal.toString());
            entityManager.merge(step);
        }
    }
}

祝你好运!