监控和指标

从 4.2 版本开始,Spring Batch 提供了对基于Micrometer的批处理监控和指标的支持。本节介绍了哪些指标是开箱即用的,以及如何提供自定义指标。

内置指标

指标收集不需要任何特定配置。框架提供的所有指标都在 前缀 下注册在Micrometer 的全局注册表中。spring.batch下表详细解释了所有指标:

指标名称

类型

描述

标签

spring.batch.job

TIMER

作业执行的持续时间

name,status

spring.batch.job.active

LONG_TASK_TIMER

目前活跃的职位

name

spring.batch.step

TIMER

步骤执行的持续时间

name, job.name,status

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标签可以 是SUCCESS或FAILURE。

自定义指标

如果您想在自定义组件中使用自己的指标,我们建议直接使用 Micrometer API。以下是如何计时的示例Tasklet:

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 中没有禁用千分尺指标的功能,这应该在千分尺方面完成。由于 Spring Batch 使用spring.batch前缀将指标存储在 micrometer 的全局注册表中,因此可以使用以下代码段将 micrometer 配置为忽略/拒绝批处理指标:

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

有关详细信息,请参阅千分尺的参考文档。


1. see XML Configuration