Spring Boot Actuator 介绍

更新于 2025-12-30

José Carlos Valero Sánchez 2025-08-24

1. 概述

在本教程中,我们将介绍 Spring Boot Actuator。首先涵盖基础知识,然后详细讨论 Spring Boot 中提供的功能。

我们将学习如何在 Spring Boot 和 WebFlux 中使用、配置和扩展这一监控工具,并充分利用响应式编程模型的优势。

Spring Boot Actuator 自 2014 年 4 月起随首个 Spring Boot 版本一同发布。

从 Spring Boot 2 开始,Actuator 被重新设计,并新增了多个令人兴奋的端点(endpoints)。

我们将本指南分为三个主要部分:

  • 什么是 Actuator?
  • Spring Boot Actuator
  • Spring Boot 3 中的 SBOM 端点

2. 什么是 Actuator?

本质上,Actuator 为我们的应用程序带来了生产就绪(production-ready)的功能。

通过引入该依赖,监控应用、收集指标、了解流量或数据库状态等操作变得轻而易举。

该库的主要优势在于:我们无需自行实现这些功能,即可获得适用于生产环境的工具。

Actuator 主要暴露运行中应用程序的操作信息——如健康状况(health)、指标(metrics)、基本信息(info)、线程转储(dump)、环境变量(env)等。它通过 HTTP 端点或 JMX Bean 与我们交互。

一旦将该依赖加入 classpath,多个端点将默认可用。与大多数 Spring 模块一样,我们可以轻松地以多种方式对其进行配置或扩展。

2.1 快速入门

我们需要在构建工具中添加 spring-boot-actuator 依赖以启用 Spring Boot Actuator。

Maven 示例:

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

注意:无论使用哪个 Spring Boot 版本,上述写法均有效,因为版本由 Spring Boot 的 Bill of Materials (BOM) 统一管理。


3. Spring Boot Actuator

Spring Boot Actuator 保留了其核心目标,同时简化了模型、扩展了能力,并改进了默认配置。

3.1 技术支持

新版 Actuator 不再绑定于特定框架,而是技术无关的(technology-agnostic)。其模型设计为可插拔且可扩展,从而在不依赖特定框架的前提下实现灵活性。

因此,借助这一新模型,我们可以使用 MVC 或 WebFlux 作为底层 Web 技术。

此外,未来的新技术也可以通过实现适当的适配器进行集成。

JMX 仍然被支持,用于在无需额外代码的情况下暴露端点。

3.2 重要变更

与旧版不同,Actuator 默认禁用大部分端点

默认仅启用两个端点:/health/info

若希望启用所有端点,可设置:

management.endpoints.web.exposure.include=*

或者显式列出需要启用的端点。

此外,Actuator 现在与应用程序的安全配置共享同一套安全规则,大幅简化了安全模型。

因此,如果项目中使用了 Spring Security,则需调整安全规则以允许访问 Actuator 端点。例如:

@Bean
public SecurityFilterChain securityWebFilterChain(HttpSecurity http) throws Exception {
    return http
      .authorizeHttpRequests(auth -> auth
        .requestMatchers("/actuator/**").permitAll()
        .anyRequest().authenticated())
      .build();
}

更多详情请参考 Actuator 官方文档

另外,所有 Actuator 端点现在默认位于 /actuator 路径下。

与旧版一样,可通过 management.endpoints.web.base-path 属性自定义该路径。

3.3 预定义端点

以下是可用的端点(部分为新增,部分已移除或重构):

  • /auditevents:列出安全审计事件(如用户登录/登出),支持按主体(principal)或类型等字段过滤。
  • /beans:返回 BeanFactory 中所有可用的 Bean,不支持过滤。
  • /conditions(原 /autoconfig):生成自动配置条件的报告。
  • /configprops:获取所有 @ConfigurationProperties Bean。
  • /env:返回当前环境属性,也可查询单个属性。
  • /flyway:提供 Flyway 数据库迁移详情。
  • /health:汇总应用程序的健康状态。
  • /heapdump:生成并返回 JVM 的堆转储(heap dump)。
  • /info:返回通用信息,如自定义数据、构建信息或最新提交详情。
  • /liquibase:与 /flyway 类似,但用于 Liquibase。
  • /logfile:返回普通应用日志(需配置 logging.file.namelogging.file.path)。
  • /loggers:查询和修改应用的日志级别。
  • /metrics:提供应用指标,包括通用指标和自定义指标。
  • /prometheus:返回 Prometheus 格式的指标数据。
  • /scheduledtasks:提供应用内所有定时任务的详情。
  • /sessions:列出 HTTP 会话(需使用 Spring Session)。
  • /shutdown:执行应用的优雅关闭(默认禁用)。
  • /threaddump:转储 JVM 的线程信息。

3.4 Actuator 端点的超媒体支持

Spring Boot 提供了一个发现端点(discovery endpoint),返回所有可用 Actuator 端点的链接,便于发现端点及其 URL。

默认可通过 /actuator 访问该发现端点。

向该 URL 发送 GET 请求,将返回如下格式的链接:

{
  "_links": {
    "self": {
      "href": "http://localhost:8080/actuator",
      "templated": false
    },
    "beans": {
      "href": "http://localhost:8080/actuator/beans",
      "templated": false
    },
    "caches-cache": {
      "href": "http://localhost:8080/actuator/caches/{cache}",
      "templated": true
    }
    // ...
  }
}

如上所示,/actuator 端点在 _links 字段下列出所有可用端点。

若配置了自定义管理基础路径(如 management.endpoints.web.base-path=/mgmt),则应通过 /mgmt 访问发现端点。

注意:当管理基础路径设为 / 时,发现端点将被禁用,以避免与其他映射冲突。

3.5 健康指示器(Health Indicators)

与旧版类似,我们可以轻松添加自定义健康指示器。创建自定义健康端点的抽象接口保持不变,但新增了 ReactiveHealthIndicator 接口以支持响应式健康检查。

示例:一个简单的响应式健康检查:

@Component
public class DownstreamServiceHealthIndicator implements ReactiveHealthIndicator {

    @Override
    public Mono<Health> health() {
        return checkDownstreamServiceHealth().onErrorResume(
          ex -> Mono.just(new Health.Builder().down(ex).build())
        );
    }

    private Mono<Health> checkDownstreamServiceHealth() {
        // 可使用 WebClient 进行响应式健康检查
        return Mono.just(new Health.Builder().up().build());
    }
}

健康指示器的一个实用特性是支持分层聚合。例如,可将所有下游服务归入 downstream-services 分类,只要其中每个服务可达,该分类即为健康。

3.6 健康组(Health Groups)

Spring Boot 现在允许将健康指示器组织为“组”,以便对组内所有成员应用一致的配置。

例如,在 application.properties 中创建名为 custom 的健康组:

management.endpoint.health.group.custom.include=diskSpace,ping

此时,调用 /actuator/health 将在响应中包含该组:

{"status":"UP","groups":["custom"]}

调用 /actuator/health/custom 可查看该组的聚合结果:

{"status":"UP"}

可通过配置显示更多细节:

management.endpoint.health.group.custom.show-components=always
management.endpoint.health.group.custom.show-details=always

此时响应将包含组件详情:

{
  "status": "UP",
  "components": {
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 499963170816,
        "free": 91300069376,
        "threshold": 10485760
      }
    },
    "ping": {
      "status": "UP"
    }
  }
}

也可配置仅对授权用户显示详情:

management.endpoint.health.group.custom.show-components=when_authorized
management.endpoint.health.group.custom.show-details=when_authorized

此外,还可自定义状态码映射。例如,当 custom 组状态为 UP 时返回 HTTP 207:

management.endpoint.health.group.custom.status.http-mapping.up=207

3.7 Spring Boot 中的指标(Metrics)

Spring Boot 内置的指标系统已被 Micrometer 取代,因此存在破坏性变更。若应用曾使用 GaugeServiceCounterService,这些类将不再可用。

Spring Boot 会自动配置 MeterRegistry Bean,允许我们直接与 Micrometer 交互。

Micrometer 已成为 Actuator 的依赖项,只要引入 Actuator 依赖即可使用。

/metrics 端点的响应格式也已彻底重构:

{
  "names": [
    "jvm.gc.pause",
    "jvm.buffer.memory.used",
    "jvm.memory.used",
    // ...
  ]
}

要获取具体指标值,需访问对应路径,如 /actuator/metrics/jvm.gc.pause

{
  "name": "jvm.gc.pause",
  "measurements": [
    { "statistic": "Count", "value": 3.0 },
    { "statistic": "TotalTime", "value": 7.9E7 },
    { "statistic": "Max", "value": 7.9E7 }
  ],
  "availableTags": [
    {
      "tag": "cause",
      "values": ["Metadata GC Threshold", "Allocation Failure"]
    },
    {
      "tag": "action",
      "values": ["end of minor GC", "end of major GC"]
    }
  ]
}

指标现在包含更丰富的值和元数据。

3.8 自定义 /info 端点

/info 端点保持不变。可通过 Maven/Gradle 插件添加 Git 提交信息:

<plugin>
    <groupId>pl.project13.maven</groupId>
    <artifactId>git-commit-id-plugin</artifactId>
</plugin>

也可通过 Spring Boot 插件包含构建信息(名称、组、版本等):

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>build-info</goal>
            </goals>
        </execution>
    </executions>
</plugin>

3.9 创建自定义端点

Spring Boot 重新设计了自定义端点的创建方式,以支持技术无关的新范式。

以下是一个用于查询、启用和禁用功能开关(feature flags)的端点示例:

@Component
@Endpoint(id = "features")
public class FeaturesEndpoint {

    private Map<String, Feature> features = new ConcurrentHashMap<>();

    @ReadOperation
    public Map<String, Feature> features() {
        return features;
    }

    @ReadOperation
    public Feature feature(@Selector String name) {
        return features.get(name);
    }

    @WriteOperation
    public void configureFeature(@Selector String name, Feature feature) {
        features.put(name, feature);
    }

    @DeleteOperation
    public void deleteFeature(@Selector String name) {
        features.remove(name);
    }

    public static class Feature {
        private Boolean enabled;
        // getters and setters
    }
}

关键点:

  • 使用 @Component 注册为 Bean。
  • 使用 @Endpoint(id = "features") 定义端点 ID,对应路径为 /actuator/features
  • 操作注解:
    • @ReadOperation → HTTP GET
    • @WriteOperation → HTTP POST
    • @DeleteOperation → HTTP DELETE

启动应用后,Spring Boot 会自动注册该端点。日志中将显示类似如下内容(以 WebFlux 为例):

Mapped "{[/actuator/features], methods=[GET]}"
Mapped "{[/actuator/features/{name}], methods=[GET]}"
Mapped "{[/actuator/features/{name}], methods=[POST]}"
Mapped "{[/actuator/features/{name}], methods=[DELETE]}"

切换至 MVC 时无需修改代码,框架会自动适配。

新模型的重要变化:

  • 无 MVC 依赖。
  • 不再有 sensitiveenabled 等元数据方法,但可通过 @Endpoint(enableByDefault = false) 控制启用状态。
  • 无需继承特定接口。
  • 支持 @DeleteOperation(旧版仅支持读/写)。

3.10 扩展现有端点

假设我们希望确保生产环境的应用不是 SNAPSHOT 版本,可通过扩展 /info 端点实现:若为 SNAPSHOT,则返回不同的 HTTP 状态码。

使用 @EndpointWebExtension 扩展预定义端点:

@Component
@EndpointWebExtension(endpoint = InfoEndpoint.class)
public class InfoWebEndpointExtension {

    private InfoEndpoint delegate;

    public InfoWebEndpointExtension(InfoEndpoint delegate) {
        this.delegate = delegate;
    }

    @ReadOperation
    public WebEndpointResponse<Map> info() {
        Map<String, Object> info = this.delegate.info();
        Integer status = getStatus(info);
        return new WebEndpointResponse<>(info, status);
    }

    private Integer getStatus(Map<String, Object> info) {
        // 若为 SNAPSHOT,返回 5xx 状态码
        return 200;
    }
}

3.11 启用所有端点

要通过 HTTP 访问 Actuator 端点,需同时启用暴露它们。

默认情况下:

  • /shutdown 外,所有端点均已启用
  • /health/info暴露

暴露所有端点:

management.endpoints.web.exposure.include=*

显式启用特定端点(如 /shutdown):

management.endpoint.shutdown.enabled=true

暴露所有端点但排除某个(如 /loggers):

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=loggers

3.12 定时任务端点(Scheduled Tasks Endpoint)

scheduledtasks 端点提供应用定时任务的信息,包括类型、目标和调度详情。

还暴露元数据,如上次执行时间、状态和下次执行时间。

请求示例:

curl 'http://localhost:8080/actuator/scheduledtasks' -i -X GET

响应示例:

{
  "cron": [
    {
      "runnable": {
        "target": "com.example.JobConfig.scheduleTaskUsingCronExpression"
      },
      "expression": "0 15 10 15 * ?",
      "nextExecution": { "time": "2025-01-15T06:45:00Z" }
    }
  ],
  "fixedDelay": [
    {
      "runnable": { "target": "..." },
      "initialDelay": 0,
      "interval": 1000,
      "lastExecution": { "time": "...", "status": "SUCCESS" },
      "nextExecution": { "time": "..." }
    }
  ],
  "fixedRate": [ /* ... */ ],
  "custom": []
}

3.13 SBOM 端点

软件物料清单(SBOM) 描述了构建软件所用的所有组件、库和依赖项,对识别和管理安全漏洞至关重要。

Spring Boot 3.3.0 内置支持 CycloneDX 格式的 SBOM。

步骤:

  1. pom.xml 中添加插件:
<plugin>
    <groupId>org.cyclonedx</groupId>
    <artifactId>cyclonedx-maven-plugin</artifactId>
    <executions>
        <execution>
            <phase>generate-resources</phase>
            <goals>
                <goal>makeAggregateBom</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <projectType>application</projectType>
        <outputDirectory>${project.build.outputDirectory}/META-INF/sbom</outputDirectory>
        <outputFormat>json</outputFormat>
        <outputName>application.cdx</outputName>
    </configuration>
</plugin>

Spring Boot 父 POM 会自动管理该插件版本。

  1. 执行 mvn package,SBOM 将生成并嵌入 JAR 文件的 META-INF/sbom/application.cdx.json 中。

  2. 暴露 SBOM 端点(默认未暴露):

management.endpoints.web.exposure.include=sbom
  1. 启动应用后,查询端点:
curl http://localhost:8080/actuator/sbom
# 返回: {"ids":["application"]}

curl -i http://localhost:8080/actuator/sbom/application
# 返回 CycloneDX JSON 格式的完整 SBOM

SBOM 包含依赖项的哈希值、许可证、问题跟踪链接等详细信息。

3.14 SSL Bundle 指标端点(Spring Boot 3.5.0-M1 新增)

Actuator 3.5.0-M1 引入了 SSL 指标,用于监控 SSL 证书,支持主动证书管理。

提供两个关键指标:

  • ssl.chains:统计证书链数量及其状态(valid, expired, will-expire-soon, not-yet-valid)。
  • ssl.chain.expiry:跟踪每个证书链距离过期的秒数。

配置示例(application.properties):

spring.ssl.bundle.jks.server.keystore.location=classpath:ssl/baeldung.p12
spring.ssl.bundle.jks.server.keystore.password=password
spring.ssl.bundle.jks.server.keystore.type=PKCS12
server.ssl.bundle=server
server.ssl.enabled=false

查询示例:

  • 获取证书链状态:
curl 'https://localhost:8080/actuator/metrics/ssl.chains'

响应:

{
  "name": "ssl.chains",
  "measurements": [{ "statistic": "VALUE", "value": 1 }],
  "availableTags": [{
    "tag": "status",
    "values": ["valid", "expired", "will-expire-soon", "not-yet-valid"]
  }]
}
  • 获取有效证书链数量:
curl 'https://localhost:8080/actuator/metrics/ssl.chains?tag=status:valid'
  • 获取证书过期时间(秒):
curl 'https://localhost:8080/actuator/metrics/ssl.chain.expiry'

响应包含 chaincertificatebundle 等标签,便于过滤。


4. 结论

本文介绍了 Spring Boot Actuator:

  • 首先定义了 Actuator 的概念及其作用;
  • 重点讲解了如何在 Spring Boot 中使用、配置和扩展 Actuator;
  • 讨论了新版中的重要安全变更;
  • 详细说明了常用端点及其变化;
  • 最后演示了如何自定义和扩展现有端点。

通过 Actuator,开发者可以轻松获得生产级监控能力,显著提升应用的可观测性和运维效率。