提供反馈和信息性消息

由于 Spring Batch 作业可能运行很长时间,因此提供进度信息通常至关重要。例如,利益相关者可能希望在批处理作业的部分或全部失败时收到通知。Spring Batch 通过以下方式支持收集此信息:

  • 主动轮询

  • 事件驱动的监听器

当异步启动 Spring Batch 作业时(例如,通过使用 Job Launching Gateway),会返回一个 JobExecution 实例。因此,您可以使用 JobExecution.getJobInstanceId() 通过使用 JobExplorerJobRepository 中检索更新的 JobExecution 实例来持续轮询状态更新。但是,这被认为不是最佳的,更推荐使用事件驱动的方法。

因此,Spring Batch 提供了监听器,包括最常用的三个监听器:

  • StepListener

  • ChunkListener

  • JobExecutionListener

在下图中所示的示例中,Spring Batch 作业已配置 StepExecutionListener。因此,Spring Integration 接收并处理任何步骤之前或之后的事件。例如,您可以使用 Router 检查接收到的 StepExecution。根据检查结果,可以发生各种事情(例如将消息路由到邮件出站通道适配器),以便可以根据某些条件发送电子邮件通知。

Handling Informational Messages
图 1. 处理信息性消息

以下两部分示例展示了如何配置监听器,以将 StepExecution 事件的消息发送到 Gateway,并将其输出记录到 logging-channel-adapter

首先,创建通知集成 Bean。

  • Java

  • XML

以下示例展示了如何在 Java 中创建通知集成 Bean

Java 配置
@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

XML 配置
<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 中添加步骤级监听器

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 中添加步骤级监听器

XML 配置
<job id="importPayments">
    <step id="step1">
        <tasklet ../>
            <chunk ../>
            <listeners>
                <listener ref="notificationExecutionsListener"/>
            </listeners>
        </tasklet>
        ...
    </step>
</job>
© . This site is unofficial and not affiliated with VMware.