Spring Boot Actuator 监控 + 可观测性 -----21
内置监控端点、自定义健康检查、动态运维能力、OpenTelemetry 链路追踪、Trace ID 透传。基于 Spring Boot 3.x 自动配置,极少代码实现生产级可观测能力,严格遵循行业最佳实践。
一、项目结构(极简 5 个文件)
plaintext
com.example.observability
├── ObservabilityApplication.java # 启动类
├── config
│ ├── CustomHealthIndicator.java # 自定义健康检查
│ └── TraceIdFilter.java # 全局响应返回Trace ID
└── controller
└── DemoController.java # 测试接口
配置文件:
src/main/resources/application.yml二、第一步:pom.xml 核心依赖
xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> </parent> <groupId>com.example</groupId> <artifactId>actuator-observability-demo</artifactId> <version>1.0.0</version> <properties> <java.version>17</java.version> </properties> <dependencies> <!-- Web 基础 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Actuator 内置监控端点(核心)对应215集 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- Prometheus 指标格式(生产监控标准)对应218集 --> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> <!-- OpenTelemetry 链路追踪桥接 对应221~223集 --> <!-- 零侵入自动生成调用链路,无需手写代码 --> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing-bridge-otel</artifactId> </dependency> <!-- Lombok 简化代码 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> </project>
三、第二步:全局配置 application.yml
一次性配置好:端点暴露规则、健康详情、应用元数据、链路采样、日志格式、日志文件
yaml
spring: application: name: observability-demo # ========== Actuator 监控配置(对应215~220集) ========== management: endpoints: web: exposure: # 暴露所有端点(学习用);生产建议只暴露 health,info,prometheus include: "*" endpoint: health: show-details: always # 健康检查显示详细信息 shutdown: enabled: true # 开启远程停机端点(对应220集,生产谨慎开启) info: env: enabled: true # 开启info元数据端点(对应219集) # 应用元数据(info端点返回,对应219集) info: app: name: observability-demo version: 1.0.0 author: demo description: Spring Boot 可观测性演示项目 # ========== 日志配置(打印Trace ID) ========== logging: pattern: console: "%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] [%X{traceId}/%X{spanId}] %logger{36} : %msg%n" file: name: ./logs/app.log # 日志文件路径,可通过 /actuator/logfile 在线查看 # ========== 链路追踪配置(对应222~223集) ========== tracing: sampling: probability: 1.0 # 采样率:1.0=全采样(学习用),生产建议0.1~0.3
四、第三步:启动类
java
运行
package com.example.observability; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ObservabilityApplication { public static void main(String[] args) { SpringApplication.run(ObservabilityApplication.class, args); } }
五、第四步:自定义健康检查(对应 216 集)
扩展系统健康检查,增加业务维度的健康状态监控
java
运行
package com.example.observability.config; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; /** * 自定义业务健康检查 * 访问 /actuator/health 时会自动包含此检查项 */ @Component public class CustomHealthIndicator implements HealthIndicator { @Override public Health health() { // 这里可以写真实的业务检查逻辑: // 比如第三方接口连通性、缓存状态、队列堆积量等 boolean bizServiceIsUp = true; if (bizServiceIsUp) { return Health.up() .withDetail("status", "业务服务正常") .withDetail("queueSize", 12) .build(); } else { return Health.down() .withDetail("error", "业务服务异常") .build(); } } }
六、第五步:全局 Trace ID 透传(对应 225 集)
所有接口响应头自动返回
X-Trace-Id,前端可直接获取,用于问题排查java
运行
package com.example.observability.config; import io.micrometer.tracing.Tracer; import jakarta.servlet.*; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import java.io.IOException; /** * 全局过滤器:所有响应头自动添加 Trace ID * 对应225集:让客户端能看到Trace ID */ @Component @RequiredArgsConstructor public class TraceIdFilter implements Filter { private final Tracer tracer; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResp = (HttpServletResponse) response; // 从链路上下文获取当前Trace ID,放入响应头 if (tracer.currentSpan() != null) { String traceId = tracer.currentSpan().context().traceId(); httpResp.addHeader("X-Trace-Id", traceId); } chain.doFilter(request, response); } }
七、第六步:测试接口
java
运行
package com.example.observability.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Slf4j @RestController @RequestMapping("/api/demo") public class DemoController { @GetMapping("/hello") public String hello() { log.info("收到hello请求"); return "Hello Observability!"; } @GetMapping("/user/{id}") public String getUser(@PathVariable Long id) { log.info("查询用户信息,userId={}", id); // 模拟业务处理 return "用户" + id + "的信息"; } }
八、核心功能验证方式
1. Actuator 常用端点(对应 215~220 集)
启动后浏览器直接访问:
表格
| 端点地址 | 功能说明 | 对应课程 |
|---|---|---|
http://localhost:8080/actuator |
所有可用端点列表 | 215 |
http://localhost:8080/actuator/health |
应用健康状态(含自定义检查) | 216 |
http://localhost:8080/actuator/info |
应用元数据信息 | 219 |
http://localhost:8080/actuator/beans |
Spring 容器所有 Bean | 217 |
http://localhost:8080/actuator/env |
环境变量与配置 | 217 |
http://localhost:8080/actuator/metrics |
运行指标列表 | 218 |
http://localhost:8080/actuator/prometheus |
Prometheus 格式指标 | 218 |
http://localhost:8080/actuator/logfile |
在线查看日志文件 | 220 |
http://localhost:8080/actuator/loggers |
动态调整日志级别(POST) | 220 |
POST /actuator/shutdown |
远程优雅停机应用 | 220 |
2. 可观测性验证(对应 221~225 集)
- 调用
http://localhost:8080/api/demo/hello - 查看控制台日志:每行日志都自动带有
[traceId/spanId] - 查看响应头:自动包含
X-Trace-Id字段,前端可直接获取
九、课程对应表
表格
| 集数 | 核心内容 | 对应代码 / 配置 |
|---|---|---|
| 215 | Actuator 内置健康监控 | pom.xml 引入 actuator + 基础端点 |
| 216 | 健康检查使用与扩展 | CustomHealthIndicator 自定义健康检查 |
| 217 | 查看 Bean、配置、环境变量 | /actuator/beans、/actuator/env 端点 |
| 218 | 指标、日志、映射实时洞察 | metrics、prometheus、logfile 端点 |
| 219 | 应用元数据智能暴露 | info 配置 + /actuator/info 端点 |
| 220 | 停机、缓存、日志控制高级用法 | shutdown 端点、loggers 动态调级别 |
| 221 | 可观测性与 OpenTelemetry 介绍 | OTel 依赖引入 + 自动配置 |
| 222 | 可观测技术栈(Micrometer/OTEL/LGTM) | micrometer-tracing-bridge-otel 桥接 |
| 223 | 极少代码实现可观测性 | 自动配置,零侵入生成链路 |
| 224 | 链路、指标、日志实战 | 日志打印 traceId + Prometheus 指标 |
| 225 | 客户端可见 Trace ID | TraceIdFilter 全局响应头透传 |
十、生产级最佳实践总结
-
端点安全
- 生产环境绝对不要
include: "*",只暴露必要的health, info, prometheus - 敏感端点加 Spring Security 保护,设置账号密码才能访问
shutdown端点生产默认关闭,需要时再开启
- 生产环境绝对不要
-
链路追踪
- 生产环境采样率不要 100%,建议 10%~30%,降低性能损耗
- Trace ID 统一透传到响应头,方便前后端联合排查问题
- 日志必须打印 traceId,实现日志 - 链路关联
-
指标监控
- 统一用 Prometheus 格式,对接 Grafana 可视化
- 核心业务接口自定义业务指标(下单量、注册量等)
-
健康检查
- 除了系统默认检查,补充核心依赖的健康检查(数据库、缓存、MQ、第三方接口)
- 健康检查详情只对内网暴露,公网只返回 UP/DOWN 状态

浙公网安备 33010602011771号