Actuator + Micrometer 抓取 SpringBoot 项目 JVM 指标方案
Actuator + Micrometer 抓取 SpringBoot 项目 JVM 指标方案
我使用的 Springboot 版本 2.7.X actuator 部分官网文档
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>添加配置
配置为体验使用暴漏全部 endpoints,生产或测试环境注意安全问题。
management:
endpoints:
web:
exposure:
# 代表开启全部监控
include: "*"
management:
metrics:
tags:
# 项目名
application: device-iot查看指标页面
打开访问页面:http://localhost:10010/actuator/prometheus,查看是否有指标项
配置 Prometheus 抓取 target
global:
scrape_interval: 10s
scrape_configs:
- job_name: 'jvm_device_iot'
# 指定抓取的路径
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['192.168.53.117:10010']Grafana 直接导入 JVM Dashboard
推荐以下 Dashboard ID:
⭐ JVM 官方 Dashboard:12900
⭐ 全套 JVM + GC + Thread Dashboard:4701
Grafana → Import → 输入 ID → Done

安全
endpoint 是什么
endpoint 是我们使用 Spring Boot Actuator 最需要关心的对象,列举一些你可能感兴趣的 endpoint
| ID | Description |
|---|---|
| beans | 查看 Spring 容器中的所有对象 |
| configprops | 查看被 @ConfigurationProperties 修饰的对象列表 |
| env | 查看 application.yaml 配置的环境配置信息 |
| health | 健康检查端点 |
| info | 应用信息 |
| metrics | 统计信息 |
| mappings | 服务契约 @RequestMapping 相关的端点 |
| shutdown | 优雅下线 |
例如 health,只需要访问如下 endpoint 即可获取应用的状态
curl "localhost:8080/actuator/health"endpoint 的 enable 和 exposure 状态
Spring Boot Actuator 针对于所有 endpoint 都提供了两种状态的配置
- enabled 启用状态。默认情况下除了
shutdown之外,其他 endpoint 都是启用状态。这也很好理解,其他 endpoint 基本都是查看行为,shutdown 却会影响应用的运行状态。 - exposure 暴露状态。endpoint 的 enabled 设置为 true 后,还需要暴露一次,才能够被访问,默认情况下只有 health 和 info 是暴露的。
enabled 不启用时,相关的 endpoint 的代码完全不会被 Spring 上下文加载,所以 enabled 为 false 时,exposure 配置了也无济于事。
几个典型的配置示例如下
暴露所有 endpoint
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
shutdown:
enabled: true只启用并暴露指定 endpoint
management:
endpoints:
enabled-by-default: false
web:
exposure:
include: "info"
endpoint:
info:
enabled: true禁用所有 endpoint
management:
endpoints:
enabled-by-default: false或者,去除掉 spring-boot-starter-actuator 依赖!
Spring Boot Actuator 的安全风险
从上文的介绍可知,有一些 Spring Boot Actuator 提供的 endpoint 是会将应用重要的信息暴露出去的,以 env 为例来感受下,能看到所有的配置文件。

安全建议
针对 Spring Boot Actuator 提供的 endpoint,采取以下几种措施,可以尽可能降低被安全攻击的风险
- 最小粒度暴露 endpoint。只开启并暴露真正用到的 endpoint,而不是配置:
management.endpoints.web.exposure.include=*。 - 为 endpoint 配置独立的访问端口,从而和 web 服务的端口分离开,避免暴露 web 服务时,误将 actuator 的 endpoint 也暴露出去。例:
management.port=8099。 - 引入
spring-boot-starter-security依赖,为 actuator 的 endpoint 配置访问控制。 - 慎重评估是否需要引入
spring-boot-stater-actuator。以我个人的经验,我至今还没有遇到什么需求是一定需要引入spring-boot-stater-actuator才能解决,如果你并不了解上文所述的安全风险,我建议你先去除掉该依赖。
完~