Spring Boot 自帶監控功能 Actuator,能夠幫助實現對程序內部運行狀況監控,好比監控情況、Bean加載狀況、環境變量、日誌信息、線程信息等。這一節結合 Prometheus 、Grafana 來更加直觀的展現這些信息。java
服務名 | 地址 | 端口 |
---|---|---|
Prometheus | 172.16.2.101 | 9090 |
Grafana | 172.16.2.101 | 3000 |
Spring Boot Demo | 172.16.2.204 | 8080 |
建立用於測試的 Spring Boot 項目,主要代碼以下。git
<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>
複製代碼
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
metrics:
tags:
application: actuator-demo
複製代碼
@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.yml 中添加針對該 Spring Boot 應用 的監控 jobgithub
- job_name: 'actuator-demo'
metrics_path: '/prometheus'
static_configs:
- targets: ['172.16.2.204:8080']
複製代碼
運行 Prometheus 和 Grafana:web
docker start prometheus grafana
複製代碼
訪問 Prometheus UI http://172.16.2.101:9090 ,查看 targets ,能夠看到 job 處於 UP 狀態,說明配置成功了。spring
Grafana UI http://172.16.2.101:3000,經過Grafana的 + 圖標導入(Import) JVM (Micrometer) dashboard:docker
查看JVM (Micormeter) dashboard:shell
能夠看到應用的 JVM 的 堆棧、 線程、 IO 等等信息。springboot
micrometer.io/docs/regist…
prometheus.io/docs/promet…app