Untitled :: Spring Batch 参考文档
提供信息性消息反馈
由于Spring Batch作业可能运行时间较长,提供进度信息通常至关重要。例如,利益相关者可能希望在批处理作业的部分或全部失败时收到通知。Spring Batch通过以下方式支持收集此类信息:
-
主动轮询
-
事件驱动监听器
当异步启动Spring Batch作业时(例如,通过使用作业启动网关),会返回一个JobExecution实例。因此,你可以使用JobExecution.getJobInstanceId(),通过JobExplorer从JobRepository中检索JobExecution的更新实例来持续轮询状态更新。然而,这种方法被认为不够理想,更推荐采用事件驱动的方式。
因此,Spring Batch 提供了多种监听器,其中最常用的三种包括:
-
StepListener -
ChunkListener -
JobExecutionListener
在下图所示的示例中,一个Spring Batch作业已配置了StepExecutionListener。因此,Spring Integration能够接收并处理步骤执行前后的任何事件。例如,您可以通过使用Router来检查接收到的StepExecution。根据检查结果,可以执行多种操作(例如将消息路由到邮件出站通道适配器),从而基于特定条件发送电子邮件通知。

图 1. 处理信息性消息
以下两部分示例展示了如何配置一个监听器,使其能够将 StepExecution 事件的消息发送到 Gateway,并将其输出记录到 logging-channel-adapter。
首先,创建通知集成 Bean。
- Java
- XML
以下示例展示了如何在 Java 中创建通知集成 Bean:
@Bean
@ServiceActivator(inputChannel = "stepExecutionsChannel")
public LoggingHandler loggingHandler() {
LoggingHandler adapter = new LoggingHandler(LoggingHandler.Level.WARN);
adapter.setLoggerName("TEST_LOGGER");
adapter.setLogExpressionString("headers.id + ': ' + payload");
return adapter;
}
@MessagingGateway(name = "notificationExecutionsListener", defaultRequestChannel = "stepExecutionsChannel")
public interface NotificationExecutionListener extends StepExecutionListener {}
您需要在配置中添加 @IntegrationComponentScan 注解。
以下示例展示了如何在 XML 中创建通知集成 Bean:
<int:channel id="stepExecutionsChannel"/>
<int:gateway id="notificationExecutionsListener"
service-interface="org.springframework.batch.core.listener.StepExecutionListener"
default-request-channel="stepExecutionsChannel"/>
<int:logging-channel-adapter channel="stepExecutionsChannel"/>
其次,修改你的任务以添加步骤级监听器。
- Java
- XML
以下示例展示了如何在 Java 中添加步骤级监听器:
public Job importPaymentsJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder("importPayments", jobRepository)
.start(new StepBuilder("step1", jobRepository)
.chunk(200, transactionManager)
.listener(notificationExecutionsListener())
// ...
.build();
)
.build();
}
以下示例展示了如何在 XML 中添加步骤级监听器:
<job id="importPayments">
<step id="step1">
<tasklet ../>
<chunk ../>
<listeners>
<listener ref="notificationExecutionsListener"/>
</listeners>
</tasklet>
...
</step>
</job>