当前位置: 首页 > news >正文

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

文章目录

    • 前言
    • 一、管理 Endpoints
      • 1. 开启与禁用 Endpoints
        • ✅ 配置方式
        • 🔁 禁用所有 Endpoint 后手动开启指定的
    • 二、常用 Endpoint 介绍
    • 三、Health Endpoint 详解
      • 1. 作用
      • 2. 默认健康检查项
      • 3. 示例:查看健康状态
    • 四、Metrics Endpoint 使用(配合 Prometheus)
      • 1. 添加依赖
      • 2. 配置启用 Metrics 和 Prometheus
      • 3. 访问 Metrics
    • 五、自定义 Endpoint 实战
      • 1. 创建自定义 Endpoint
        • 步骤 1:创建 Controller
      • 2. 使用 Spring Boot Actuator 的标准方式(推荐)
        • 示例:创建 `custom-health` Endpoint
        • 配置启用该 Endpoint
        • 访问地址
    • 六、安全控制
      • 1. 启用认证
        • 方式一:Spring Security + JWT
    • 七、总结
    • 八、最佳实践建议
    • 九、参考文档


前言

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

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


一、管理 Endpoints

1. 开启与禁用 Endpoints

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

✅ 配置方式
management:endpoint:beans:enabled: truehealth:enabled: trueinfo:enabled: false

说明

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

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

management:endpoints:web:exposure:include: health,info,metricsendpoint:health:enabled: trueinfo:enabled: truemetrics:enabled: truebeans: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: trueendpoints:web:exposure:include: metricsmetrics: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
@Component
@Endpoint(id = "custom-health")
public class CustomHealthEndpoint {private final HealthIndicator healthIndicator;public CustomHealthEndpoint(HealthIndicator healthIndicator) {this.healthIndicator = healthIndicator;}@ReadOperationpublic 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: trueendpoints: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,metricsbase-path: /actuator

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

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected 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 的监控能力!


http://www.dtcms.com/a/581049.html

相关文章:

  • 【软考】信息系统项目管理师-资源管理论文范文
  • 标准nodejs项目工程
  • 定制网站开发公司种子网站模板
  • Maven前奏
  • C++面试高级篇——内存管理(一)
  • kanass零基础学习,如何进行工时管理,有效度量项目资源
  • 恋爱ppt模板免费下载网站官方网站建立
  • Spark-3.5.7文档1 - 快速开始
  • Java_Map接口实现类Properties
  • 【底层机制】Android对Linux线程调度的移动设备优化深度解析
  • 2025制品管理工具选型,Jfrog or Hadess一文全面测评
  • 3.2、Python-元组
  • PyTorch之父发离职长文,告别Meta
  • 微信小程序与网站连接厦门 网站优化
  • 网站小图标怎么做的多就能自己做网站
  • 江阴规划建设局网站跨境电商开店要多少钱
  • 系统分析师大题介绍
  • 包装产线数字化转型实战:从数据采集到智能决策的效能提升之路
  • Flutter for HarmonyOS开发指南(四):国际化与本地化深度实践
  • Java:RocketMQ消息发送报错:MQClientException: No route info of this topic: topic_xxx
  • 青少年机器人技术等级考试理论综合试卷(一级)2019年3月
  • 产品经理画原型工具 axure
  • 云端硬盘详解:认识 Persistent Disk(持久磁盘)
  • 西安给大学做网站公司郑州网站seo服务
  • Java 8 Optional 类实战:从根源杜绝空指针异常的优雅方案
  • 面向强化学习的状态空间建模:RSSM的介绍和PyTorch实现(4)
  • openGauss安装部署详细教程
  • 用Visual Studio Code最新版开发C#应用程序
  • 修改llama index的prompte template(提示词模板)的解决方案
  • 在星河社区部署大模型unsloth/Llama-3.3-70B-Instruct-GGUF