引语
SpringBoot升级到2.0后,重构了很大一部分代码,导致原官方提供SpringBoot-Starter不再适用,可以用io.micrometer:micrometer-registry-prometheus
配合spring-boot-starter-actuator
适用,笔者通过实践验证可以实现,但发现采集的指标过多,包括JVM等监控指标,笔者只想暴露自己自定义的一种指标,未搜索到可以关闭部分指标的配置,于是准备从源码入手完成实现
参考官方实现,基于SpringBoot Actuator,给出一种简单的实现思路,直接贴出代码
依赖项【笔者基于Gradle,Maven类似】:
buildscript {
ext["springBootVersion"] = "2.2.7.RELEASE"
}
// 依赖版本管理
dependencyManagement {
dependencies {
imports {
mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}"
}
dependency "io.prometheus:simpleclient:0.8.1"
}
}
}
// 添加依赖
compile "org.springframework.boot:spring-boot-starter-actuator"
compile 'io.prometheus:simpleclient'
自定义类一:
@WebEndpoint(id = "prometheus")
public class MyPrometheusEndpoint {
private final CollectorRegistry collectorRegistry;
public MyPrometheusEndpoint(CollectorRegistry collectorRegistry) {
this.collectorRegistry = collectorRegistry;
}
@ReadOperation(produces = TextFormat.CONTENT_TYPE_004)
public String scrape() {
try {
Writer writer = new StringWriter();
TextFormat.write004(writer, this.collectorRegistry.metricFamilySamples());
return writer.toString();
} catch (IOException ex) {
// This actually never happens since StringWriter::write() doesn't throw any
// IOException
throw new RuntimeException("Writing metrics failed", ex);
}
}
}
自定义类二:
@Configuration
public class MyPrometheusMetricsExportAutoConfiguration {
public static final CollectorRegistry collectorRegistry = new CollectorRegistry();
@Bean
public MyPrometheusEndpoint myPrometheusEndpoint() {
return new MyPrometheusEndpoint(collectorRegistry);
}
}
自定义类三【指标搜集类,自定义Collector】:
@Component
@Slf4j
public class MonitorCheckExporter extends Collector {
@Override
public List<MetricFamilySamples> collect() {
List<MetricFamilySamples> mfs = new ArrayList<>();
/*
* 指标采集逻辑
* */
return mfs;
}
}
SpringBoot启动类:
public class Application implements CommandLineRunner {
@Resource
private MonitorCheckExporter monitorCheckExporter;
public static void main(String[] args) {
SpringApplication sa = new SpringApplication(Application.class);
sa.run(args);
}
@Override
public void run(String... args) throws Exception {
monitorCheckExporter.register(MyPrometheusMetricsExportAutoConfiguration.collectorRegistry);
}
}
至此,可实现SpringBoot2.0暴露/actuator/prometheus接口供prometheus拉取自定义指标的功能