添加依赖
<!-- prometheus指标埋点 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
配置application.yml
配置项可参考SpringBoot2.x系列教程之SpringBoot2.x配置大全03。注意的是management.metrics.distribution.sla的新版本将sla -> slo
management:
endpoints:
web:
exposure:
include: prometheus # 打开 Prometheus 的 Web 访问 Path
metrics:
# 下面选项建议打开,以监控 http 请求的 P99/P95 等,具体的时间分布可以根据实际情况设置
distribution:
slo:
http:
server:
requests: 1ms,5ms,10ms,50ms,100ms,200ms,500ms,1s,5s
# 在 Prometheus 中添加特别的 Labels
tags:
# 必须加上对应的应用名,因为需要以应用的维度来查看对应的监控
application: reptile-data-platform-display
本地验证
- security 放行 “/actuator/**”
- 运行项目后访问http://localhost:8080/actuator/prometheus 访问到 Prometheus 协议的指标数据,说明相关的依赖配置已经正确。
例子中配置默认配置,对应的端口和路径以实际项目为准
自定义指标
有下面两种方式,以官方的两个实例讲解
- prometheus SDK中自带的Counter、Gauge、Histogram、Summary类型build
- 继承Collector 实现collect()方法添加自定义指标
@Component
public class MyPrometheusConfig {
@Autowired
private CollectorRegistry collectorRegistry;
@Bean
public Counter requestTotalCountCollector() {
return Counter.build()
// 用于指定该指标的名称
.name("http_requests_total")
// 用于声明该metrics拥有的维度label
.labelNames("path", "method", "code")
.help("http请求总计数").register(collectorRegistry);
}
@Bean
@Primary
public YourCustomCollector yourCustomCollector(){
return new YourCustomCollector().register(collectorRegistry);
}
}
public class YourCustomCollector extends Collector{
@Override
public List<MetricFamilySamples> collect() {
List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
// With no labels.
mfs.add(new GaugeMetricFamily("my_gauge", "help", 42));
// 创建metrics指标
GaugeMetricFamily labeledGauge = new GaugeMetricFamily("my_other_gauge", "help", Arrays.asList("labelname"));
// 设置指标的label以及value
labeledGauge.addMetric(Arrays.asList("foo"), new Random().nextInt(5));
labeledGauge.addMetric(Arrays.asList("bar"), new Random().nextInt(5));
mfs.add(labeledGauge);
return mfs;
}
}
添加这两个类后再/actuator/prometheus中找一下http_requests_total、my_gauge、my_other_gauge这三个指标名称
在prometheus.yml中配置节点
- job_name: 'reptile_node'
static_configs:
- targets: ['localhost:8080']
metrics_path: "/actuator/prometheus"