插件窝 干货文章 Spring Boot Actuator端点大揭秘:轻松监控你的应用程序

Spring Boot Actuator端点大揭秘:轻松监控你的应用程序

端点 Actuator public 定义 850    来源:    2025-04-20

Spring Boot Actuator端点大揭秘:轻松监控你的应用程序

什么是Actuator?

Spring Boot Actuator是一个强大的子项目,它为Spring Boot应用程序提供了生产级别的监控和管理功能。通过Actuator,开发者可以轻松地获取应用程序的运行状态、性能指标、配置信息等,而无需自己实现这些功能。

核心Actuator端点

1. 健康检查端点 (/actuator/health)

{
  "status": "UP",
  "components": {
    "db": {
      "status": "UP",
      "details": {
        "database": "H2",
        "validationQuery": "isValid()"
      }
    },
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 500105249792,
        "free": 356682842112,
        "threshold": 10485760
      }
    }
  }
}

2. 信息端点 (/actuator/info)

{
  "app": {
    "name": "demo-application",
    "version": "1.0.0",
    "description": "Spring Boot Actuator Demo"
  },
  "build": {
    "artifact": "demo",
    "name": "demo",
    "time": "2023-05-15T12:40:12.123Z",
    "version": "1.0.0",
    "group": "com.example"
  }
}

3. 指标端点 (/actuator/metrics)

{
  "names": [
    "jvm.memory.max",
    "process.uptime",
    "system.cpu.count",
    "jvm.threads.live",
    "logback.events"
  ]
}

4. 环境信息端点 (/actuator/env)

{
  "activeProfiles": ["dev"],
  "propertySources": [
    {
      "name": "server.ports",
      "properties": {
        "local.server.port": {
          "value": 8080
        }
      }
    },
    {
      "name": "servletContextInitParams",
      "properties": {}
    }
  ]
}

如何启用Actuator

  1. 添加依赖到pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  1. 配置端点暴露方式(在application.propertiesapplication.yml中):
# 暴露所有端点(生产环境慎用)
management.endpoints.web.exposure.include=*
# 或选择性暴露
management.endpoints.web.exposure.include=health,info,metrics

自定义Actuator端点

1. 自定义健康指示器

@Component
public class CustomHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // 实现自定义健康检查逻辑
        boolean isHealthy = checkSomething();

        if (isHealthy) {
            return Health.up()
                .withDetail("customService", "Available")
                .build();
        }
        return Health.down()
            .withDetail("customService", "Not Available")
            .build();
    }
}

2. 自定义信息贡献者

@Component
public class CustomInfoContributor implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("customInfo", 
            Collections.singletonMap("description", "This is custom info"));
    }
}

安全配置

为了保护敏感端点,建议配置安全访问:

@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/actuator/health").permitAll()
                .antMatchers("/actuator/info").permitAll()
                .antMatchers("/actuator/**").hasRole("ADMIN")
            .and()
            .httpBasic();
    }
}

高级功能

1. 自定义指标

@Service
public class MyService {

    private final Counter counter;

    public MyService(MeterRegistry registry) {
        this.counter = registry.counter("my.service.calls");
    }

    public void doSomething() {
        // 业务逻辑
        counter.increment();
    }
}

2. 自定义端点

@Endpoint(id = "features")
@Component
public class FeaturesEndpoint {

    private Map<String, Boolean> features = new ConcurrentHashMap<>();

    @ReadOperation
    public Map<String, Boolean> features() {
        return features;
    }

    @WriteOperation
    public void configureFeature(@Selector String name, boolean enabled) {
        features.put(name, enabled);
    }
}

最佳实践

  1. 生产环境安全:确保敏感端点受到保护,不要暴露所有端点
  2. 监控集成:将Actuator与Prometheus、Grafana等监控工具集成
  3. 健康检查:为关键依赖项(数据库、外部服务)实现健康指示器
  4. 自定义指标:添加业务相关指标以更好地了解应用性能
  5. 日志管理:结合Logback或Log4j2使用Actuator的日志级别端点

通过合理配置和使用Spring Boot Actuator,你可以轻松实现应用程序的全面监控和管理,大大提高生产环境的可观察性和运维效率。