Spring 如何使用StepListenerSupport
我正在尝试根据超时值停止正在运行的作业。我正在跟踪一篇找到的帖子,但我不确定您是如何添加此侦听器的 下面是侦听器实现Spring 如何使用StepListenerSupport,spring,spring-boot,spring-batch,Spring,Spring Boot,Spring Batch,我正在尝试根据超时值停止正在运行的作业。我正在跟踪一篇找到的帖子,但我不确定您是如何添加此侦听器的 下面是侦听器实现 public class StopListener extends StepListenerSupport{ public static final Logger LOG = LoggerFactory.getLogger(StopListener.class); private static final int TIMEOUT = 30; privat
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();
}
@Bean
公共步骤dataFilterStep(){
返回stepBuilderFactory.get(“dataFilterStep”)
.chunk(10)
.reader(dataFilterItemReader())
.processor(dataFilterItemProcessor())
.writer(dataFilterWriter())
.listener(新的StopListener())
.build();
}
但我得到的错误是“方法侦听器(对象)对于类型SimpleTestBuilder是不明确的”。非常感谢您的帮助 一方面,
StepListenerSupport
是一个多态对象,它实现了。另一方面,step builder提供了几个重载的.listener()
方法来接受不同类型的侦听器。这就是为什么在.listener(new StopListener())
中传递StopListener
时,侦听器的类型不明确
您可以将侦听器强制转换为所需的类型,例如:
.listener(((ChunkListener) new StopListener()))
但是,通过遵循最小功耗原则[1][2],我建议更改StopListener
,以仅实现功能所需的接口。在您的情况下,您似乎希望在afterChunk
中的给定超时后停止作业,这样您就可以让侦听器实现ChunkListener
,而不是扩展StepListenerSupport
- [1] :
- [2] :
StepListenerSupport
是一个多态对象,它实现了。另一方面,step builder提供了几个重载的.listener()
方法来接受不同类型的侦听器。这就是为什么在.listener(new StopListener())
中传递StopListener
时,侦听器的类型不明确
您可以将侦听器强制转换为所需的类型,例如:
.listener(((ChunkListener) new StopListener()))
但是,通过遵循最小功耗原则[1][2],我建议更改StopListener
,以仅实现功能所需的接口。在您的情况下,您似乎希望在afterChunk
中的给定超时后停止作业,这样您就可以让侦听器实现ChunkListener
,而不是扩展StepListenerSupport
- [1] :
- [2] :