通过信息性消息提供反馈
由于 Spring Batch 作业可能运行较长时间,提供进度信息通常至关重要。例如,相关方可能希望在批处理作业的某些或全部部分失败时收到通知。Spring Batch 支持通过以下方式收集此类信息:
-
主动轮询
-
事件驱动监听器
当异步启动 Spring Batch 作业(例如,通过使用作业启动网关)时,将返回一个 JobExecution 实例。因此,您可以使用 JobExecution.getJobInstanceId() 通过 JobExplorer 从 JobRepository 检索更新的 JobExecution 实例,从而持续轮询状态更新。然而,这种方式被认为不是最优的,更推荐采用事件驱动的方法。
因此,Spring Batch 提供了监听器,包括三个最常用的监听器:
-
StepListener -
ChunkListener -
JobExecutionListener
在以下图像所示的示例中,Spring Batch 作业已配置为StepExecutionListener。因此,Spring Integration 会接收并处理任何步骤之前或之后的事件。例如,您可以使用Router检查接收到的StepExecution。根据该检查的结果,可能会发生各种情况(例如将消息路由到邮件出站通道适配器),从而可以根据某些条件发送电子邮件通知。
以下两部分示例展示了如何配置监听器,以便在发生 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>