【SpringBoot】34 核心功能 - 指标监控- Spring Boot Actuator 指标监控开启与禁用与 Endpoint 定制

【SpringBoot】34 核心功能 - 指标监控- Spring Boot Actuator 指标监控开启与禁用与 Endpoint 定制


前言

在现代微服务架构中,应用的可观测性(Observability)至关重要。Spring Boot Actuator 提供了一套强大的生产就绪功能,帮助开发者监控和管理应用程序。其中,Endpoints 是 Actuator 的核心组件,它们暴露了应用程序的运行时信息,如健康状态、性能指标、配置信息等。

本文将深入探讨如何开启与禁用 Endpoints,以及如何定制自定义 Endpoint,并结合实际示例进行详细讲解。


一、管理 Endpoints

1. 开启与禁用 Endpoints

Spring Boot 默认开启了大多数 Endpoint,但有些(如 shutdown)是关闭的。我们可以通过配置文件灵活控制每个 Endpoint 的启用状态。

✅ 配置方式
management:
  endpoint:
    beans:
      enabled: true
    health:
      enabled: true
    info:
      enabled: false

说明

  • management.endpoint.<endpointName>.enabled = true/false 控制单个 Endpoint 是否启用。
  • 所有 Endpoint 默认都是开启的,除了 shutdown
🔁 禁用所有 Endpoint 后手动开启指定的

如果你希望更安全地控制访问,可以先禁用所有 Endpoint,再手动开启需要的:

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
  endpoint:
    health:
      enabled: true
    info:
      enabled: true
    metrics:
      enabled: true
    beans:
      enabled: false

说明

  • management.endpoints.web.exposure.include 指定通过 Web 暴露的 Endpoint 列表。
  • 即使 beans 被设置为 false,但由于 include 中未包含它,所以不会暴露。
  • 这种方式可以实现“白名单”机制,增强安全性。

二、常用 Endpoint 介绍

Endpoint 用途
health 监控应用健康状况(如数据库连接、Redis 等)
metrics 查看运行时指标(如 JVM 内存、GC、HTTP 请求统计等)
info 显示应用基本信息(如版本、构建号等)
beans 显示 Spring 容器中所有 Bean 的列表
env 显示环境变量和配置属性
configprops 显示所有 @ConfigurationProperties 类的配置

📌 注意:这些 Endpoint 可以通过 HTTP 访问,例如:

http://localhost:8080/actuator/health
http://localhost:8080/actuator/metrics

三、Health Endpoint 详解

1. 作用

health Endpoint 用于返回应用当前的健康状态,常用于 CI/CD 平台或监控系统(如 Prometheus、Grafana)定期检查服务是否可用。

2. 默认健康检查项

Spring Boot 默认会自动检测以下组件的健康状态:

  • 数据库连接(如 DataSource)
  • Redis
  • RabbitMQ
  • Kafka
  • JMX

这些检查由 HealthIndicator 接口实现,你可以轻松添加自定义检查。

3. 示例:查看健康状态

访问:

GET /actuator/health

返回示例:

{
  "status": "UP",
  "details": {
    "db": {
      "status": "UP",
      "database": "H2",
      "error": null
    },
    "diskSpace": {
      "status": "UP",
      "total": 100000000000,
      "free": 50000000000,
      "threshold": 10485760
    }
  }
}

status: UP 表示应用正常运行。


四、Metrics Endpoint 使用(配合 Prometheus)

1. 添加依赖

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

2. 配置启用 Metrics 和 Prometheus

management:
  endpoint:
    metrics:
      enabled: true
  endpoints:
    web:
      exposure:
        include: metrics
  metrics:
    export:
      prometheus:
        enabled: true

3. 访问 Metrics

访问:

GET /actuator/prometheus

返回内容为 Prometheus 格式文本,例如:

# HELP jvm_memory_used_bytes Used memory
# TYPE jvm_memory_used_bytes gauge
jvm_memory_used_bytes{area="heap",} 123456789.0
jvm_memory_used_bytes{area="nonheap",} 23456789.0

✅ 这些数据可被 Prometheus 抓取,用于绘图、告警等。


五、自定义 Endpoint 实战

1. 创建自定义 Endpoint

假设我们要创建一个 custom-info Endpoint,展示应用的自定义信息。

步骤 1:创建 Controller
@RestController
@RequestMapping("/actuator")
public class CustomInfoEndpoint {

    @GetMapping("/custom-info")
    public Map<String, Object> customInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("app-name", "MyApp");
        info.put("version", "1.0.0");
        info.put("env", "production");
        info.put("timestamp", new Date());
        return info;
    }
}

⚠️ 注意:此方式仅适用于简单场景,不推荐用于复杂逻辑。


2. 使用 Spring Boot Actuator 的标准方式(推荐)

使用 @Endpoint 注解来创建符合规范的 Endpoint。

示例:创建 custom-health Endpoint
@***ponent
@Endpoint(id = "custom-health")
public class CustomHealthEndpoint {

    private final HealthIndicator healthIndicator;

    public CustomHealthEndpoint(HealthIndicator healthIndicator) {
        this.healthIndicator = healthIndicator;
    }

    @ReadOperation
    public Health health() {
        // 自定义健康检查逻辑
        if (someCondition()) {
            return Health.up().withDetail("message", "Custom health check passed").build();
        } else {
            return Health.down().withDetail("message", "Custom health check failed").build();
        }
    }

    private boolean someCondition() {
        // 模拟业务条件
        return true;
    }
}
配置启用该 Endpoint
management:
  endpoint:
    custom-health:
      enabled: true
  endpoints:
    web:
      exposure:
        include: custom-health
访问地址
GET /actuator/custom-health

返回示例:

{
  "status": "UP",
  "details": {
    "message": "Custom health check passed"
  }
}

六、安全控制

1. 启用认证

默认情况下,Actuator Endpoint 是无认证的,建议启用安全保护。

方式一:Spring Security + JWT
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
      base-path: /actuator

然后在 Security 配置中限制访问:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

七、总结

功能 说明
Endpoint 启用/禁用 使用 management.endpoint.<name>.enabled 控制
白名单暴露 使用 management.endpoints.web.exposure.include
Health Endpoint 返回应用健康状态,支持自定义检查
Metrics Endpoint 支持 Prometheus,用于监控
自定义 Endpoint 使用 @Endpoint + @ReadOperation 等注解
安全控制 建议结合 Spring Security 保护敏感接口

八、最佳实践建议

  1. 不要暴露所有 Endpoint:只暴露必要的,如 health, info, metrics
  2. 启用认证:生产环境必须对 Actuator 接口做权限控制。
  3. 使用 Prometheus + Grafana:构建完整的监控体系。
  4. 自定义健康检查:根据业务需求添加关键服务检查。
  5. 日志与报警联动:当健康状态变为 DOWN 时触发告警。

九、参考文档

  • Spring Boot Actuator 官方文档
  • Micrometer 官方文档
  • Prometheus 官网

通过合理配置和使用 Actuator 的 Endpoints,我们可以极大提升应用的可观测性和运维效率。希望本文能帮助你更好地理解和实践 Spring Boot 的监控能力!


转载请说明出处内容投诉
CSS教程网 » 【SpringBoot】34 核心功能 - 指标监控- Spring Boot Actuator 指标监控开启与禁用与 Endpoint 定制

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买