文章首發(fā)于公眾號(hào)《程序員果果》
地址:https://mp.weixin.qq.com/s/MWQImwMhcFglmHZ4lIcxVA
本篇源碼:https://github.com/gf-huanchupk/SpringBootLearning
簡(jiǎn)介
Spring Boot 自帶監(jiān)控功能 Actuator拷呆,可以幫助實(shí)現(xiàn)對(duì)程序內(nèi)部運(yùn)行情況監(jiān)控错沽,比如監(jiān)控狀況、Bean加載情況袍啡、環(huán)境變量、日志信息、線程信息等。這一節(jié)結(jié)合 Prometheus 慕的、Grafana 來(lái)更加直觀的展示這些信息。
實(shí)驗(yàn)
說(shuō)明
服務(wù)名 | 地址 | 端口 |
---|---|---|
Prometheus | 172.16.2.101 | 9090 |
Grafana | 172.16.2.101 | 3000 |
Spring Boot Demo | 172.16.2.204 | 8080 |
創(chuàng)建項(xiàng)目
創(chuàng)建用于測(cè)試的 Spring Boot 項(xiàng)目挤渔,主要代碼如下肮街。
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
application.yml
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
metrics:
tags:
application: actuator-demo
- management.endpoints.web.exposure.include:大多數(shù)actuator的端口都不會(huì)通過(guò)http公開(kāi),* 代表公開(kāi)所有這些端點(diǎn)判导。對(duì)于生產(chǎn)環(huán)境嫉父,應(yīng)該仔細(xì)選擇要公開(kāi)的端點(diǎn)。
- management.metrics.tags.application:為應(yīng)用設(shè)置 tag 眼刃,方便區(qū)分不同的應(yīng)用绕辖。
啟動(dòng)類(lèi)
@SpringBootApplication
@RestController
public class SpringbootActuatorPrometheusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootActuatorPrometheusDemoApplication.class, args);
}
@RequestMapping(value = "/hello")
public String sayHello() {
for (int i = 1 ; i <= 10 ; i++) {
Thread t = new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} , "HelloThread - " + i);
t.start();
}
return "ok";
}
/**
@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config().commonTags("application", "springboot-actuator-prometheus-demo");
}
*/
}
配置 Prometheus 和 Grafana
在 prometheus.yml 中添加針對(duì)該 Spring Boot 應(yīng)用 的監(jiān)控 job
- job_name: 'actuator-demo'
metrics_path: '/prometheus'
static_configs:
- targets: ['172.16.2.204:8080']
運(yùn)行 Prometheus 和 Grafana:
docker start prometheus grafana
訪問(wèn) Prometheus UI http://172.16.2.101:9090 ,查看 targets 擂红,可以看到 job 處于 UP 狀態(tài)仪际,說(shuō)明配置成功了。
Grafana UI http://172.16.2.101:3000昵骤,通過(guò)Grafana的 + 圖標(biāo)導(dǎo)入(Import) JVM (Micrometer) dashboard:
- grafana id = 4701
- 注意選中prometheus數(shù)據(jù)源
查看JVM (Micormeter) dashboard:
可以看到應(yīng)用的 JVM 的 堆棧树碱、 線程、 IO 等等信息变秦。
源碼
https://github.com/gf-huanchupk/SpringBootLearning/tree/master/springboot-actuator-prometheus
參考
https://micrometer.io/docs/registry/prometheus
https://prometheus.io/docs/prometheus