
1. Spring Boot Actuator 入门指南Spring Boot Actuator 是 Spring Boot 提供的一个强大模块专门用于监控和管理生产环境中的应用程序。想象一下你的应用就像一辆汽车而 Actuator 就是仪表盘让你随时掌握车辆的各项运行指标。要在项目中集成 Actuator 非常简单只需要在 pom.xml 中添加以下依赖dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-actuator/artifactId /dependency添加依赖后Actuator 就会自动提供一系列开箱即用的监控端点。这些端点就像是应用程序的体检报告可以告诉你应用的健康状况、性能指标等关键信息。默认情况下Actuator 只暴露了 /health 和 /info 两个端点。要查看所有可用的端点可以在 application.properties 中添加配置management.endpoints.web.exposure.include*启动应用后访问 http://localhost:8080/actuator 就能看到所有可用的端点列表。每个端点都提供了特定的监控功能比如/health应用健康状态/metricsJVM 和系统指标/loggers查看和修改日志级别/threaddump线程转储信息/heapdump堆内存转储2. 核心端点详解与配置2.1 健康检查端点 (/health)健康检查端点是生产环境中最常用的端点之一。默认情况下它只会返回一个简单的状态{ status: UP }要让健康检查显示更多细节可以添加配置management.endpoint.health.show-detailsalways这样返回的信息会更丰富{ status: UP, components: { db: { status: UP, details: { database: MySQL, validationQuery: isValid() } }, diskSpace: { status: UP, details: { total: 500107862016, free: 91300069376, threshold: 10485760 } } } }2.2 指标端点 (/metrics)/metrics 端点提供了丰富的 JVM 和系统指标数据。在 Spring Boot 2.x 之后指标系统基于 Micrometer 实现支持对接多种监控系统如 Prometheus。访问 /metrics 会返回所有可用的指标名称{ names: [ jvm.memory.max, jvm.threads.live, process.cpu.usage, system.cpu.count ] }要查看具体指标的值可以访问 /metrics/{指标名称}比如 /metrics/jvm.memory.used{ name: jvm.memory.used, measurements: [ { statistic: VALUE, value: 115023872 } ], availableTags: [] }2.3 日志端点 (/loggers)/loggers 端点允许你在运行时动态调整日志级别这在生产环境排查问题时非常有用。例如要临时开启 DEBUG 日志curl -X POST http://localhost:8080/actuator/loggers/com.example \ -H Content-Type: application/json \ -d {configuredLevel:DEBUG}3. 生产环境高级配置3.1 端点安全保护暴露监控端点虽然方便但也带来了安全风险。Spring Security 可以很好地与 Actuator 集成保护这些端点Configuration EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole(ADMIN) .anyRequest().permitAll() .and() .httpBasic(); } }这段配置确保只有 ADMIN 角色的用户才能访问 Actuator 端点。同时建议在生产环境中启用 HTTPS 来加密通信。3.2 自定义健康指示器除了内置的健康检查你还可以创建自定义的健康指示器。比如检查第三方 API 是否可用Component public class ApiHealthIndicator implements HealthIndicator { Override public Health health() { int status checkApiStatus(); if (status ! 0) { return Health.down() .withDetail(Error Code, status) .build(); } return Health.up().build(); } private int checkApiStatus() { // 实现你的检查逻辑 return 0; // 0表示正常 } }3.3 自定义端点如果内置端点不能满足需求你可以创建自定义端点Component Endpoint(id features) public class FeaturesEndpoint { private MapString, Boolean features new ConcurrentHashMap(); ReadOperation public MapString, Boolean features() { return features; } WriteOperation public void updateFeature(Selector String name, boolean enabled) { features.put(name, enabled); } }这个自定义端点允许你通过 HTTP 动态启用/禁用功能开关。4. 生产级监控体系搭建4.1 与 Prometheus 集成要将 Actuator 指标导出到 Prometheus首先添加依赖dependency groupIdio.micrometer/groupId artifactIdmicrometer-registry-prometheus/artifactId /dependency然后在配置中暴露 Prometheus 端点management.endpoints.web.exposure.includehealth,info,prometheusPrometheus 会定期从 /actuator/prometheus 拉取指标数据。4.2 使用 Grafana 可视化结合 Grafana 可以创建丰富的监控仪表盘。Spring Boot 官方提供了几个现成的仪表盘模板JVM 监控仪表盘Spring MVC 指标仪表盘缓存指标仪表盘这些仪表盘可以直接导入到你的 Grafana 实例中。4.3 告警配置在 Prometheus 中可以配置基于指标的告警规则例如groups: - name: springboot.rules rules: - alert: HighHeapUsage expr: jvm_memory_used_bytes{areaheap} / jvm_memory_max_bytes{areaheap} 0.8 for: 5m labels: severity: warning annotations: summary: High heap usage on {{ $labels.instance }} description: Heap usage is {{ $value }}%当堆内存使用超过 80% 持续 5 分钟时就会触发告警。5. 实战经验与避坑指南在实际项目中使用 Actuator 时我总结了一些经验教训端点暴露策略生产环境不要暴露所有端点特别是 /env 和 /heapdump 这样的敏感端点。建议只暴露必要的端点management.endpoints.web.exposure.includehealth,info,metrics,prometheus性能考虑某些端点如 /heapdump 会触发完整的内存转储可能导致应用短暂停顿。建议在低峰期使用这些操作。健康检查聚合在微服务架构中可以使用 Spring Cloud 的健康检查聚合功能通过 /health 端点检查所有依赖服务的状态。自定义指标利用 Micrometer 添加业务指标比如订单创建速率、API 响应时间等RestController public class OrderController { private final Counter orderCounter; public OrderController(MeterRegistry registry) { this.orderCounter registry.counter(orders.created); } PostMapping(/orders) public Order createOrder() { orderCounter.increment(); // 创建订单逻辑 } }版本兼容性升级 Spring Boot 版本时要注意 Actuator 端点的变化。例如 Spring Boot 2.5 默认不再暴露 /info 端点。通过这些实战经验你可以构建一个既安全又强大的生产级监控系统确保应用的健康稳定运行。