監控與指標

自 4.2 版本以來,Spring Batch 基於 Micrometer 提供了批處理監控和指標支援。本節介紹框架提供的內建指標以及如何貢獻自定義指標。

內建指標

指標收集不需要任何特定配置。框架提供的所有指標都註冊在 Micrometer 的全域性登錄檔(global registry)中,使用 spring.batch 字首。下表詳細解釋了所有指標:

指標名稱

型別

描述

標籤

spring.batch.job

TIMER

作業執行持續時間

name, status

spring.batch.job.active

LONG_TASK_TIMER

當前活動作業

name

spring.batch.step

TIMER

Step 執行持續時間

name, job.name, status

spring.batch.step.active

LONG_TASK_TIMER

當前活動 Step

name

spring.batch.item.read

TIMER

項讀取持續時間

job.name, step.name, status

spring.batch.item.process

TIMER

項處理持續時間

job.name, step.name, status

spring.batch.chunk.write

TIMER

塊寫入持續時間

job.name, step.name, status

status 標籤可以是 SUCCESSFAILURE

自定義指標

如果您想在自定義元件中使用自己的指標,我們建議直接使用 Micrometer API。以下是一個如何對 Tasklet 進行計時(timing)的示例:

import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

public class MyTimedTasklet implements Tasklet {

	@Override
	public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
		Timer.Sample sample = Timer.start(Metrics.globalRegistry);
		String status = "success";
		try {
			// do some work
		} catch (Exception e) {
			// handle exception
			status = "failure";
		} finally {
			sample.stop(Timer.builder("my.tasklet.timer")
					.description("Duration of MyTimedTasklet")
					.tag("status", status)
					.register(Metrics.globalRegistry));
		}
		return RepeatStatus.FINISHED;
	}
}

停用指標

指標收集與日誌記錄類似。停用日誌通常透過配置日誌庫來完成,指標也是如此。Spring Batch 沒有停用 Micrometer 指標的功能。這應該在 Micrometer 端完成。由於 Spring Batch 使用 spring.batch 字首將指標儲存在 Micrometer 的全域性登錄檔(global registry)中,您可以使用以下程式碼片段配置 Micrometer 忽略或拒絕批處理指標:

Metrics.globalRegistry.config().meterFilter(MeterFilter.denyNameStartsWith("spring.batch"))

有關更多詳細資訊,請參閱 Micrometer 的參考文件