Spring Batch是一个用于批处理应用程序的开源框架,它提供了许多指标(metrics),可以帮助你监控和优化批处理作业的性能。Spring Boot Actuator是一个用于监控和管理Spring Boot应用程序的模块,它提供了对Spring Batch指标的捕获和暴露。
以下是一个简单的示例代码,展示如何捕获Spring Batch的Micro指标:
首先,在你的pom.xml
文件中添加Spring Boot Actuator和Micrometer的依赖:
<dependencies>
<!-- Spring Boot Starter Batch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<!-- Spring Boot Starter Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Micrometer Core -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
</dependency>
<!-- Micrometer Prometheus (或其他监控系统) -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
</dependencies>
在你的application.yml
或application.properties
文件中配置Actuator和Micrometer:
management:
endpoints:
web:
exposure:
include: "*"
metrics:
export:
prometheus:
enabled: true
在你的Spring Boot应用程序的主类或配置类上添加@EnableBatchMetrics
注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(exclude = {BatchAutoConfiguration.class})
@EnableTask
@EnableScheduling
public class BatchApplication {
public static void main(String[] args) {
SpringApplication.run(BatchApplication.class, args);
}
}
启动你的Spring Boot应用程序后,你可以通过访问/actuator/prometheus
端点来获取Prometheus格式的指标数据:
curl http://localhost:8080/actuator/prometheus
以下是一个简单的Spring Batch作业示例:
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job job() {
return jobBuilderFactory.get("job")
.incrementer(new RunIdIncrementer())
.flow(step())
.end()
.build();
}
@Bean
protected Step step() {
return stepBuilderFactory.get("step")
.tasklet((contribution, chunkContext) -> {
System.out.println("Processing step...");
return RepeatStatus.FINISHED;
})
.build();
}
}
通过以上步骤,你可以捕获并暴露Spring Batch的Micro指标,以便进行监控和分析。
领取专属 10元无门槛券
手把手带您无忧上云