提供反饋和資訊性訊息

由於 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.