为基于JVM的应用程序提供一个数据采集门面。监控系统有很多,Prometheus、Datadog等,每个系统都有自己的数据采集方式,实现方式各有不同,如果需要更换监控系统,代码改动很大。Micrometer 就可以在中间充当门面,代码层面之和 Micrometer 交互,再由 Micrometer 和监控系统对接。
io.micrometer 的三个模块
核心模块 micrometer-core
- 数据收集SPI 核心模块
不同监控系统的实现模块 micrometer-registry-*
- 如针对 Prometheus 的 micrometer-registry-prometheus,针对datadog的micrometer-registry-dog
- 这些模块都依赖于core
- 测试模块 micrometer-test
Springboot + micrometer +Prometheus+Grafana 采集数据
Springboot
配置pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
// 配置micrometer prometheus插件
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<scope>runtime</scope>
</dependency>配置application.yml
management:
endpoints:
web:
exposure:
// 配置需要加载的断点
include: health, metrics, trace, prometheus编写测试接口
@RestController
public class TestController {
private Counter counter;
// 注入meterRegistry
public TestController(MeterRegistry meterRegistry ) {
this.counter = meterRegistry.counter("demo.http.requests.total", Tags.of("uri","/hello"));
}
@RequestMapping("/hello")
public String hello() {
counter.increment();
return "Hello World";
}
}测试接口
curl http://localhost:8088/hello
Hello World%
// 查看health
curl http://localhost:8088/actuator/health
// 查看 metrics 指标,可以看到所有监控的指标。
// "demo.http.requests.total"是自定义的指标
curl http://localhost:8088/actuator/metrics
{
"names": [
"demo.http.requests.total",
"http.server.requests",
......
"tomcat.sessions.expired",
"tomcat.sessions.rejected"
]
}
// 此接口可以查询 metrics 指标的具体值
curl http://localhost:8088/actuator/metrics/demo.http.requests.total
// 此接口开放给 prometheus 采集metrics数据
curl http://localhost:8088/actuator/prometheusPrometheus
- 配置prometheus.yml
在scrape_configs下增加配置
- job_name:job名称
- mtrics_paty:默认路径 /metrics ,prometheus监控springboot的路径是 /actuator/prometheus
static_configs:
- targets 可以配置多个,[ip : port],应用的ip端口
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: "prometheus"
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ["localhost:9090"]
- job_name: "micrometer-test"
# metrics_path defaults to '/metrics'
metrics_path: "/actuator/prometheus"
# scheme defaults to 'http'.
static_configs:
- targets: ["192.168.31.152:8088"]- 重启Prometheus
在Prometheus根目录下直接执行
./prometheus
会自动加载同在根目录下的 prometheus.yml
或者 --conifg 指定配置文件
prometheus --conifg=/xx/xx/prometheus.yml- 访问prometheus : localhost:9090
Grafana
Grafana 安装方法很多,任选一个即可,关键是启动 Grafana 后配置数据源和dashboard
- 配置数据源
搜索 prometheus 数据源,只需配置 url 为 prometheus 的 ip 端口即可
- 配置dashboard
直接引入官方的 JVM 仪表盘,id为4701,再选择刚才配置的数据源就可以导入了。
更多完整dashboard可以在Grafana Dashboard 找到
- 添加自定义 panel
springboot 中定义的指标demo.http.requests.total,可以添加panel。

