Skip to content

Spring Boot Actuator REST API 完全指南 🚀

什么是 Spring Boot Actuator?

Spring Boot Actuator 是 Spring Boot 框架中的一个强大模块,它为应用程序提供了生产就绪的监控和管理功能。简单来说,它就像是给你的应用装上了一套"仪表盘",让你能够实时了解应用的运行状态。

TIP

想象一下,如果你开车时没有仪表盘,你就不知道油量、速度、引擎温度等关键信息。Actuator 就是为你的 Spring Boot 应用提供这样的"仪表盘"功能。

为什么需要 Actuator? 🤔

在没有 Actuator 之前,开发者面临着这些痛点:

kotlin
// 需要手动编写各种监控接口
@RestController
class ManualHealthController {
    
    @GetMapping("/custom-health")
    fun checkHealth(): Map<String, Any> {
        // 手动检查数据库连接
        // 手动检查内存使用情况
        // 手动检查磁盘空间
        // ... 大量重复代码
        return mapOf("status" to "UP") 
    }
    
    @GetMapping("/custom-metrics")
    fun getMetrics(): Map<String, Any> {
        // 手动收集各种指标
        // 需要自己实现复杂的统计逻辑
        return mapOf() 
    }
}
kotlin
// 只需要添加依赖,自动获得所有监控功能
@SpringBootApplication
class Application

// 自动提供以下端点:
// /actuator/health - 健康检查
// /actuator/metrics - 应用指标
// /actuator/info - 应用信息
// /actuator/env - 环境变量
// ... 还有更多!

Actuator 的核心价值 ✨

1. 零配置监控

无需编写复杂的监控代码,添加依赖即可获得完整的监控体系。

2. 生产就绪

提供的所有端点都经过生产环境验证,可以直接用于线上监控。

3. 标准化输出

所有监控数据都采用标准的 JSON 格式,便于与各种监控系统集成。

快速上手 🚀

1. 添加依赖

kotlin
// build.gradle.kts
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-actuator") 
    implementation("org.springframework.boot:spring-boot-starter-web")
}

2. 基础配置

kotlin
// application.yml
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics 
      base-path: /actuator 
  endpoint:
    health:
      show-details: always

3. 创建简单的应用

kotlin
@SpringBootApplication
class ActuatorDemoApplication

fun main(args: Array<String>) {
    runApplication<ActuatorDemoApplication>(*args)
}

@RestController
class HelloController {
    
    @GetMapping("/hello")
    fun hello(): String {
        return "Hello, Actuator!"
    }
}

URL 配置详解 🔧

默认 URL 结构

Spring Boot Actuator 的所有端点默认都在 /actuator 路径下:

自定义基础路径

kotlin
// application.properties
management.endpoints.web.base-path=/manage 
kotlin
// 访问健康检查
GET /actuator/health

// 访问应用信息
GET /actuator/info

// 访问指标数据
GET /actuator/metrics
kotlin
// 访问健康检查
GET /manage/health 

// 访问应用信息
GET /manage/info 

// 访问指标数据
GET /manage/metrics 

实际应用场景

kotlin
@Configuration
class ActuatorConfig {
    
    // 生产环境配置
    @Profile("prod")
    @Bean
    fun prodActuatorConfig(): WebMvcConfigurer {
        return object : WebMvcConfigurer {
            override fun addInterceptors(registry: InterceptorRegistry) {
                // 生产环境下为 actuator 端点添加认证
                registry.addInterceptor(AuthInterceptor())
                    .addPathPatterns("/manage/**") 
            }
        }
    }
}

时间戳格式规范 ⏰

Actuator 严格遵循 ISO 8601 标准来处理所有时间相关的数据。

为什么使用 ISO 8601?

IMPORTANT

ISO 8601 是国际标准化组织制定的时间表示标准,它解决了不同系统间时间格式不统一的问题。

标准格式示例

kotlin
// 正确的时间格式示例
val timestamps = listOf(
    "2024-01-15T10:30:00Z",           // UTC 时间
    "2024-01-15T10:30:00+08:00",     // 带时区偏移
    "2024-01-15T10:30:00.123Z",      // 包含毫秒
    "2024-01-15T10:30:00.123+08:00"  // 完整格式
)

在 Actuator 中的应用

kotlin
@RestController
class CustomActuatorController {
    
    @GetMapping("/actuator/custom-audit")
    fun getAuditEvents(
        @RequestParam after: String? = null
    ): ResponseEntity<Map<String, Any>> {
        
        // after 参数必须符合 ISO 8601 格式
        // 例如: /actuator/custom-audit?after=2024-01-15T10:30:00Z
        
        val afterTime = after?.let { 
            Instant.parse(it) 
        } ?: Instant.now().minus(Duration.ofDays(1))
        
        return ResponseEntity.ok(mapOf(
            "events" to getEventsAfter(afterTime),
            "timestamp" to Instant.now().toString() 
        ))
    }
    
    private fun getEventsAfter(after: Instant): List<AuditEvent> {
        // 获取指定时间之后的审计事件
        return emptyList()
    }
}

常用端点实战 💡

1. 健康检查端点

kotlin
// 自定义健康检查
@Component
class DatabaseHealthIndicator : HealthIndicator {
    
    override fun health(): Health {
        return try {
            // 检查数据库连接
            checkDatabaseConnection()
            Health.up()
                .withDetail("database", "Available") 
                .withDetail("connections", 10)
                .build()
        } catch (e: Exception) {
            Health.down()
                .withDetail("database", "Unavailable") 
                .withException(e)
                .build()
        }
    }
    
    private fun checkDatabaseConnection() {
        // 实际的数据库连接检查逻辑
    }
}

2. 自定义信息端点

kotlin
// 添加应用信息
@Component
class AppInfoContributor : InfoContributor {
    
    override fun contribute(builder: Info.Builder) {
        builder.withDetail("app", mapOf(
            "name" to "My Awesome App",
            "version" to "1.0.0",
            "description" to "这是一个使用 Actuator 的示例应用", 
            "team" to "开发团队 A"
        ))
    }
}

3. 自定义指标

kotlin
@Service
class BusinessMetricsService {
    
    private val meterRegistry: MeterRegistry
    private val orderCounter: Counter
    
    constructor(meterRegistry: MeterRegistry) {
        this.meterRegistry = meterRegistry
        this.orderCounter = Counter.builder("orders.created") 
            .description("创建的订单数量")
            .register(meterRegistry)
    }
    
    fun processOrder(order: Order) {
        // 处理订单逻辑
        processOrderLogic(order)
        
        // 记录指标
        orderCounter.increment() 
        
        // 记录订单金额
        meterRegistry.gauge("orders.amount", order.amount) 
    }
    
    private fun processOrderLogic(order: Order) {
        // 实际的订单处理逻辑
    }
}

安全配置 🔒

在生产环境中,Actuator 端点通常包含敏感信息,需要进行适当的安全配置:

kotlin
@Configuration
@EnableWebSecurity
class ActuatorSecurityConfig {
    
    @Bean
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        return http
            .authorizeHttpRequests { requests ->
                requests
                    .requestMatchers("/actuator/health").permitAll() 
                    .requestMatchers("/actuator/**").hasRole("ADMIN") 
                    .anyRequest().authenticated()
            }
            .httpBasic { }
            .build()
    }
}

最佳实践 📋

1. 端点暴露策略

安全提醒

生产环境中不要暴露所有端点,只暴露必要的端点。

kotlin
# 生产环境配置
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics # [!code highlight]
        exclude: env,configprops,beans # [!code warning]
  endpoint:
    health:
      show-details: when-authorized # [!code highlight]

2. 监控集成

kotlin
// 与 Prometheus 集成
dependencies {
    implementation("io.micrometer:micrometer-registry-prometheus") 
}

3. 自定义端点

kotlin
@Component
@Endpoint(id = "custom")
class CustomEndpoint {
    
    @ReadOperation
    fun customInfo(): Map<String, Any> {
        return mapOf(
            "customProperty" to "customValue",
            "timestamp" to Instant.now().toString() 
        )
    }
    
    @WriteOperation
    fun updateCustomInfo(@Selector key: String, value: String) {
        // 更新自定义信息的逻辑
    }
}

总结 🎯

Spring Boot Actuator 是现代 Spring Boot 应用不可或缺的监控利器。它通过提供标准化的监控端点,让开发者能够:

  • 零配置获得完整的应用监控能力
  • 标准化的数据格式便于集成各种监控系统
  • 生产就绪的安全和性能保障
  • 可扩展的自定义监控能力

NOTE

记住,好的监控不是为了监控而监控,而是为了让你的应用更加稳定可靠,让问题在影响用户之前就被发现和解决。

通过合理配置 Actuator,你的 Spring Boot 应用将具备企业级的监控和管理能力,为生产环境的稳定运行提供强有力的保障! 🚀