SpringBoot(七)之监控
Spring Boot 提供了丰富的监控和管理功能,可以通过 Spring Boot Actuator 组件实现。Actuator 使你能够监控和管理 Spring Boot 应用程序的各个方面,比如健康检查、指标、环境信息等。以下是如何在 Spring Boot 应用程序中使用 Actuator 进行监控的详细指南。
1. 添加依赖
首先,在你的 pom.xml
(如果使用 Maven)或 build.gradle
(如果使用 Gradle)文件中添加 Spring Boot Actuator 依赖。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
2. 配置 Actuator 端点
默认情况下,Actuator 端点是关闭的或者只对本地访问开放。你可以在 application.properties
文件中配置端点的暴露和安全性。
management:
endpoint:
health:
show-details: always
info:
enabled: true
endpoints:
web:
base-path: /actuator
exposure:
include: '*'
# 暴露所有 Actuator 端点
management.endpoints.web.exposure.include=*
# 设置 Actuator 端点的访问路径前缀
management.endpoints.web.base-path=/actuator
# 配置健康检查和信息端点
management.endpoint.health.show-details=always
management.endpoint.info.enabled=true
3. 访问 Actuator 端点
Spring Boot Actuator 提供了多个有用的端点,你可以通过浏览器或工具(如 curl
)来访问这些端点。例如,如果你的应用程序在本地运行,你可以访问以下 URL 来查看健康检查和应用信息:
- 健康检查:
http://localhost:8080/actuator/health
{
"status": "UP",
"components": {
"diskSpace": {
"status": "UP",
"details": {
"total": 31114924032,
"free": 6748753920,
"threshold": 10485760,
"exists": true
}
},
"ping": {
"status": "UP"
}
}
}
- 应用信息:
http://localhost:8080/actuator/info
- 所有端点:
http://localhost:8080/actuator
4. 集成 Micrometer 进行指标监控
Micrometer 是一个应用指标记录库,Spring Boot Actuator 通过它可以与各种监控系统(如 Prometheus、Graphite、New Relic 等)集成。
添加 Micrometer 依赖(以 Prometheus 为例):
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
配置 Prometheus 指标暴露:
# 暴露 Prometheus 指标端点
management.metrics.export.prometheus.enabled=true
访问 Prometheus 指标: 配置完成后,可以通过 http://localhost:8080/actuator/prometheus
访问 Prometheus 格式的指标数据。
关于Prometheus 和 grafana的集成监控搭建请查看 https://blog.csdn.net/gaowenhui2008/article/details/131598092