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
https://github.com/gf-huanchupk/SpringBootLearning/tree/master/springboot-actuator-prometheusapp
https://micrometer.io/docs/registry/prometheus
https://prometheus.io/docs/prometheuside