如何使用 StepListenerSupport

How to use StepListenerSupport

我正在尝试根据超时值停止 运行 作业。我正在关注一个 post 发现 ,但我不确定你是如何添加这个监听器的。

这是监听器实现

public class StopListener extends StepListenerSupport{
    public static final Logger LOG = LoggerFactory.getLogger(StopListener.class);
    private static final int TIMEOUT = 30; 
    private StepExecution stepExecution;

    @Override
    public void beforeStep(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }

    @Override
    public void afterChunk(ChunkContext context) {
        if (timeout(context)) {
            this.stepExecution.setTerminateOnly();
        }
    }

    private boolean timeout(ChunkContext chunkContext) {
        LOG.info("----- TIMEOUT-----");
        Date startTime = chunkContext.getStepContext().getStepExecution().getJobExecution().getStartTime();
        Date now = new Date();
        return Duration.between(startTime.toInstant(), now.toInstant()).toMinutes() > TIMEOUT;
    }

}

这是我的步骤

@Bean
public Step dataFilterStep() {
    return stepBuilderFactory.get("dataFilterStep")
            .<UserInfo, UserInfo> chunk(10)
            .reader(dataFilterItemReader())
            .processor(dataFilterItemProcessor())
            .writer(dataFilterWriter())
            .listener(new StopListener())             
            .build();
}

但我收到错误提示“方法侦听器 (Object) 对于类型 SimpleStepBuilder 不明确”。非常感谢您的帮助!

一方面,StepListenerSupport是一个多态对象,它实现了7 interfaces。另一方面,步骤构建器提供了几个重载的 .listener() 方法来接受不同类型的侦听器。这就是为什么当你在 .listener(new StopListener()) 中传递你的 StopListener 时,监听器的类型不明确。

您可以将侦听器转换为您想要的类型,例如:

.listener(((ChunkListener) new StopListener()))

但是,根据最低功耗原则 [1][2],我建议更改您的 StopListener 以仅实现功能所需的接口。在您的情况下,您似乎想在 afterChunk 中的给定超时后停止作业,因此您可以让您的侦听器实现 ChunkListener 而不是扩展 StepListenerSupport.