第18章 SpringBoot 监控

掌握SpringBoot Actuator监控和管理功能

💻 查看完整代码 - 在线IDE体验

🎯 学习目标

  • Actuator基础:了解监控端点和配置
  • 健康检查:掌握应用健康状态监控
  • 指标监控:学习性能指标收集
  • 自定义端点:创建业务监控端点
  • 安全配置:保护监控端点安全
  • 集成监控:与外部监控系统集成

🔧 核心概念

  • Actuator:生产就绪功能监控
  • Endpoints:监控和管理端点
  • Health Indicators:健康状态指示器
  • Metrics:应用性能指标
  • Info:应用信息展示
  • Custom Endpoints:自定义监控端点

📦 依赖配置

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- Web支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 安全支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Micrometer监控 --> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency>

🔄 监控架构流程

应用启动
Actuator初始化
端点注册
健康检查
指标收集
监控展示

⚙️ 配置示例

# application.yml management: endpoints: web: exposure: include: health,info,metrics,prometheus,env,beans base-path: /actuator endpoint: health: show-details: always show-components: always info: enabled: true metrics: enabled: true health: defaults: enabled: true diskspace: enabled: true db: enabled: true info: env: enabled: true java: enabled: true os: enabled: true # 应用信息 info: app: name: SpringBoot监控示例 version: 1.0.0 description: Actuator监控功能演示 build: artifact: spring-boot-actuator-demo version: 1.0.0

📊 监控仪表板

实时监控指标

UP
应用状态
256MB
内存使用
15ms
响应时间
1,234
请求总数

🏥 健康检查配置

@Component public class CustomHealthIndicator implements HealthIndicator { @Override public Health health() { // 检查业务逻辑 boolean isHealthy = checkBusinessLogic(); if (isHealthy) { return Health.up() .withDetail("database", "连接正常") .withDetail("cache", "缓存可用") .withDetail("external-service", "服务正常") .build(); } else { return Health.down() .withDetail("error", "业务检查失败") .build(); } } private boolean checkBusinessLogic() { // 实际的健康检查逻辑 return true; } }

📈 自定义指标

@RestController public class MetricsController { private final MeterRegistry meterRegistry; private final Counter requestCounter; private final Timer requestTimer; public MetricsController(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; this.requestCounter = Counter.builder("api.requests") .description("API请求计数") .register(meterRegistry); this.requestTimer = Timer.builder("api.response.time") .description("API响应时间") .register(meterRegistry); } @GetMapping("/api/data") public String getData() { return Timer.Sample.start(meterRegistry) .stop(requestTimer); } }

🔗 监控端点

GET /actuator/health
应用健康状态检查
GET /actuator/info
应用基本信息
GET /actuator/metrics
应用性能指标
GET /actuator/env
环境变量信息
GET /actuator/beans
Spring Bean信息
GET /actuator/prometheus
Prometheus格式指标

🛡️ 安全配置

@Configuration @EnableWebSecurity public class ActuatorSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authz -> authz .requestMatchers("/actuator/health").permitAll() .requestMatchers("/actuator/info").permitAll() .requestMatchers("/actuator/**").hasRole("ADMIN") .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()); return http.build(); } } # 配置用户 spring: security: user: name: admin password: admin123 roles: ADMIN

🎛️ 自定义端点

@Component @Endpoint(id = "business") public class BusinessEndpoint { @ReadOperation public Map<String, Object> business() { Map<String, Object> details = new HashMap<>(); details.put("activeUsers", 1500); details.put("totalOrders", 25000); details.put("revenue", "¥1,250,000"); details.put("systemLoad", "正常"); return details; } @WriteOperation public void updateConfig(@Selector String key, String value) { // 更新配置逻辑 System.out.println("更新配置: " + key + " = " + value); } }

📊 监控对比

监控类型 端点 用途 安全级别
健康检查 /actuator/health 应用状态监控 公开
应用信息 /actuator/info 版本和构建信息 公开
性能指标 /actuator/metrics JVM和应用指标 受保护
环境信息 /actuator/env 配置和环境变量 受保护
Bean信息 /actuator/beans Spring容器Bean 受保护
日志配置 /actuator/loggers 动态调整日志级别 受保护

🎯 最佳实践

监控配置建议

1. 端点安全:生产环境必须配置认证和授权

2. 选择性暴露:只暴露必要的监控端点

3. 健康检查:实现业务相关的健康检查逻辑

4. 自定义指标:收集业务关键指标

5. 监控集成:与Prometheus、Grafana等工具集成

6. 告警配置:设置关键指标的告警阈值

🎉 恭喜完成第18章学习!

你已经掌握了SpringBoot Actuator监控的核心技能,接下来学习应用安全!

🚀 下一章:SpringBoot Security 🏠 返回课程首页