人人都会AI编程

17.3 应用监控:Spring Boot Actuator 端点与指标

更新时间:2026-07-10

应用上线后,最怕的不是 Bug,而是“发生了问题却一无所知”。Spring Boot Actuator 正是为此而生——它提供了一套生产级的监控端点(Endpoints),让你可以随时探查应用的内部状态、健康状况、配置信息、运行指标和环境详情。这一节将带你从基础到实践,掌握如何用 Actuator 构建可见、可诊断的应用。

17.3.1 什么是 Spring Boot Actuator

Actuator 是 Spring Boot 的一个子项目,核心目标是将应用的运行时信息以 HTTP 或 JMX 的方式暴露出去。它包含了大量开箱即用的端点,覆盖了健康检查、指标收集、配置查看、日志管理等监控场景。引入 Actuator 不需要编写任何监控代码,只需添加依赖、做适当配置,即可获得生产级的可观测能力。

17.3.2 快速启用 Actuator

1. 添加依赖

Maven 项目在 pom.xml 中加入:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Gradle 项目:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

2. 启动并访问端点

启动应用后,Actuator 默认会开启 health 端点。访问 http://localhost:8080/actuator/health,你会得到:

{"status":"UP"}

这代表应用正在运行,且所有健康指标组件检查通过。

17.3.3 核心端点速览

Actuator 提供了几十个端点,按类别整理如下,你需要哪些就暴露哪些:

健康与状态

  • health:汇总应用健康状态,常用于 K8s 的就绪探针与存活探针。
  • info:展示应用自定义信息(版本号、构建时间、Git 提交等)。

指标与统计

  • metrics:列出 JVM、HTTP 请求、数据源、缓存等上百种指标,支持筛选和汇总。
  • prometheus:以 Prometheus 文本格式暴露相同指标,供监控系统抓取(需添加 micrometer-registry-prometheus 依赖)。

配置与环境

  • env:查看所有环境属性,包括 application.properties、系统变量、命令行参数等。
  • configprops:罗列所有 @ConfigurationProperties Bean 及其当前值,检查配置是否如期加载。
  • beans:列出容器中所有 Spring Bean 的名称、作用域及依赖关系。
  • conditions:展示自动配置条件的匹配/不匹配报告,排查“为什么某个配置没有生效”的神器。

日志管理

  • loggers:查看和动态修改各个包或类的日志级别,无需重启应用。

线程与追踪

  • threaddump:打印线程堆栈快照,帮助诊断死锁或高负载。
  • heapdump:下载堆转储文件,供离线分析。

HTTP 映射

  • mappings:列出所有 @RequestMapping 映射,方便梳理 API 结构。

17.3.4 配置端点的暴露与安全

出于安全考虑,Actuator 默认只暴露 healthinfo 端点,其余需要显式开启。通过 application.properties 控制:

# 暴露所有端点(生产环境谨慎)
management.endpoints.web.exposure.include=*
# 或者只暴露特定端点
management.endpoints.web.exposure.include=health,info,metrics,loggers

# 显式排除某些端点
management.endpoints.web.exposure.exclude=env,beans

生产环境安全建议

  • 所有 Actuator 端点通过 Spring Security 保护,仅限运维角色访问。
  • health 端点可配置详情可见性:management.endpoint.health.show-details=when_authorized(仅认证用户可见详情)或 always / never
  • 调整 Actuator 的 base path(如 management.endpoints.web.base-path=/manage),避开通用扫描。

17.3.5 定制健康检查

health 端点本身是一个聚合器,它会调用所有 HealthIndicator 实现类,综合得出最终状态。Spring Boot 自动集成了常见组件的健康检查(如 DataSource、Redis、MongoDB、RabbitMQ 等),你也可以添加自定义业务健康指标。

示例:为订单服务添加健康检查

@Component
public class OrderServiceHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        // 模拟检查订单服务依赖的外部系统
        boolean externalServiceAvailable = checkExternalService();
        if (externalServiceAvailable) {
            return Health.up().withDetail("message", "订单服务外部依赖正常").build();
        } else {
            return Health.down()
                         .withDetail("message", "外部订单服务不可达")
                         .build();
        }
    }

    private boolean checkExternalService() {
        // 实际检查逻辑,如调用远程探活接口
        return true;
    }
}

访问 /actuator/health 你会看到扩展后的明细:

{
  "status": "UP",
  "components": {
    "db": {"status": "UP", "details": {"database": "MySQL"}},
    "orderService": {"status": "UP", "details": {"message": "订单服务外部依赖正常"}}
  }
}

17.3.6 定制 info 端点

info 端点的内容完全由你定义,常用于展示应用版本、构建号或联系人信息。可以通过配置属性或编程方式填充。

方式一:在 application.properties 中定义

info.app.name=@project.name@
info.app.version=@project.version@
info.app.description=@project.description@

(需要在 Maven 开启 resource filtering,Gradle 使用类似属性替换)

方式二:实现 InfoContributor

@Component
public class CustomInfoContributor implements InfoContributor {
    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("buildTime", Instant.now())
               .withDetail("gitCommit", "abc123");
    }
}

两种方式提供的信息会合并输出。

17.3.7 深入 metrics 端点

metrics 是 Actuator 中最强大的观测工具之一。它基于 Micrometer 门面,将各种指标统一抽象,并支持接入 Prometheus、Graphite、Datadog 等多种监控后端。

查看可用指标名称

访问 /actuator/metrics 会返回所有指标名列表,如:

{"names": [
    "jvm.memory.used",
    "jvm.gc.pause",
    "http.server.requests",
    "hikaricp.connections.active",
    "process.cpu.usage",
    ...
]}

查询特定指标

jvm.memory.used 为例,访问 /actuator/metrics/jvm.memory.used 可得到该指标的当前值及可用标签:

{
  "name": "jvm.memory.used",
  "measurements": [{"statistic": "VALUE", "value": 2.56E8}],
  "availableTags": [{"tag": "area", "values": ["heap", "nonheap"]}]
}

带上标签进一步过滤:/actuator/metrics/jvm.memory.used?tag=area:heap

自定义业务指标

通过注入 MeterRegistry,可以记录计数器、仪表、计时器等:

@Service
public class OrderMonitor {
    private final Counter orderCounter;

    public OrderMonitor(MeterRegistry registry) {
        this.orderCounter = Counter.builder("orders.created")
                                   .description("Orders created count")
                                   .register(registry);
    }

    public void onOrderCreated() {
        orderCounter.increment();
    }
}

之后在 metrics 端点就能查到 orders.created

17.3.8 与 Prometheus + Grafana 集成

将指标导入 Prometheus 是业界最主流的监控方案。只需添加依赖:

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

暴露 prometheus 端点后(确保 management.endpoints.web.exposure.include 包含 prometheus),Prometheus 就可以定期抓取 /actuator/prometheus。搭配 Grafana 仪表盘(如 Spring Boot 官方提供的 Dashboard ID: 10254),可实现下图所示的实时监控大屏,展示 QPS、延迟、JVM 内存、线程等关键曲线。

17.3.9 实战:为 K8s 配置存活与就绪探针

在 Kubernetes 中,Actuator 的 health 端点天然适合作为探针目标。

livenessProbe:
  httpGet:
    path: /actuator/health/liveness
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10
readinessProbe:
  httpGet:
    path: /actuator/health/readiness
    port: 8080
  initialDelaySeconds: 15
  periodSeconds: 5

你需要使用 livenessreadiness 健康组来区分探针类型(Spring Boot 2.3+ 支持),否则使用基础的 /actuator/health 也可。只需要在 application.properties 中开启相应组:

management.endpoint.health.probes.enabled=true

17.3.10 日常排障的实用姿势

  • 启动后环境不对?/actuator/env/actuator/configprops 检查最终生效的配置。
  • 自动配置未按预期工作? /actuator/conditions 告诉你哪些自动配置类被匹配、哪些因为什么条件不匹配。
  • 内存异常或请求变慢? 先看 /actuator/metrics/jvm.memory.usedhttp.server.requests,再结合 /actuator/threaddump 分析线程栈。
  • 日志调试无需重启POST /actuator/loggers/com.example 带上 {"configuredLevel": "DEBUG"} 即可在线调整日志级别。

Spring Boot Actuator 提供的不是一个炫酷的界面,而是一套严肃的生产工具链。将它配置到位,你的应用就从黑盒变成了一个透明、可诊断的现代服务。当线上告警响起时,你会庆幸提前开启了这些端点。