Spring Boot Actuator 生产级监控实战指南
Alex Chen | 2026-09-01T08:56:37 | Java, Spring Boot
深入讲解 Spring Boot Actuator 的端点配置、自定义健康检查、Micrometer 指标集成以及 Prometheus + Grafana 监控看板搭建。
# Spring Boot Actuator 生产级监控实战指南 ## 为什么需要 Actuator 在生产环境中,我们需要实时了解应用的健康状态、JVM 内存、线程池利用率等关键指标。Spring Boot Actuator 提供了开箱即用的监控能力。 ## 基础配置 ```yaml # application.yml management: endpoints: web: exposure: include: health,info,metrics,prometheus base-path: /actuator endpoint: health: show-details: when_authorized group: readiness: include: db,redis,diskSpace liveness: include: ping metrics: tags: application: my-service env: production ``` ## 自定义健康检查 ```java @Component public class ExternalApiHealthIndicator implements HealthIndicator { private final RestTemplate restTemplate; public ExternalApiHealthIndicator(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Override public Health health() { try { ResponseEntity resp = restTemplate .getForEntity("https://api.example.com/health", String.class); if (resp.getStatusCode().is2xxSuccessful()) { return Health.up() .withDetail("externalApi", "reachable") .withDetail("responseTime", System.currentTimeMillis()) .build(); } } catch (Exception e) { return Health.down(e) .withDetail("externalApi", "unreachable") .build(); } return Health.unknown().build(); } } ``` ## Micrometer 自定义指标 ```java @Service public class OrderService { private final Counter orderCounter; private final Timer orderTimer; public OrderService(MeterRegistry registry) { this.orderCounter = Counter.builder("orders.created") .description("Total orders created") .tag("type", "standard") .register(registry); this.orderTimer = Timer.builder("orders.process.time") .description("Order processing time") .publishPercentiles(0.5, 0.95, 0.99) .register(registry); } public Order createOrder(OrderRequest req) { return orderTimer.record(() -> { Order order = processOrder(req); orderCounter.increment(); return order; }); } } ``` ## Prometheus + Grafana 看板 添加 `micrometer-registry-prometheus` 依赖后,`/actuator/prometheus` 端点会暴露所有指标。在 Grafana 中导入 JVM Dashboard(ID: 4701)即可获得完整的 JVM 监控视图。 建议为生产环境单独配置告警规则,当堆内存使用超过 80% 或 GC 暂停时间超过 500ms 时触发通知。