Spring Boot Actuator 是 Spring Boot 提供的一个用于监控和管理 Spring Boot 应用程序的工具。它通过一系列预定义的端点(Endpoints),暴露应用程序的运行时信息,包括健康状态、配置属性、度量指标、线程转储等。这些端点可以通过 HTTP 接口或 JMX(Java Management Extensions)访问,帮助开发者和运维人员快速了解应用的运行状态,并进行故障排查和性能优化。本次实践教程通过 Spring Boot Actuator 将延迟数据暴露出去,并通过 Prometheus 以及 Grafana 等监控组件实现从客户端监控 Redis 命令时延。
配置 Spring Boot Actuator 组建依赖
Actuator 与 Spring Boot 深度集成,开箱即用。只需在项目的 `pom.xml` 文件中引入 Spring Boot Actuator 依赖即可,如下所示。
<!-- Spring Boot Actuator --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId><version>2.4.1</version></dependency><!-- Micrometer Prometheus Registry --><dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId></dependency>
配置暴露端点
在 Spring Boot 2.x 及以上版本中,使用 Spring Data Redis 和 Lettuce 客户端时,Lettuce 会自动与 Micrometer 集成并开始收集指标。如果引入了 Actuator 依赖,仅需在配置文件中暴露 `metrics` 和 `prometheus` 端点,即可完成 Lettuce 指标的监控和暴露。在项目的配置文件 application.properties 中,添加需要暴露的端点,如下所示。
/actuator/health:显示应用的整体健康状况,可以自定义健康指标。
/actuator/info:显示应用的定制信息,如版本、描述等。
/actuator/metrics:提供各种运行指标,如内存、CPU、HTTP 请求统计等。
/actuator/prometheus:向 Prometheus 暴露监控数据,Prometheus 可以定期抓取 Spring Boot 应用的度量指标。
management.endpoints.web.exposure.include=health,info,metrics,prometheus
使用 CURL 拉去端点数据
通过 `curl` 拉取 metrics 端点,查看 Lettuce 上报的性能指标。

通过 `curl` 请求 Prometheus 端点,可以查看按照 Prometheus 格式上报的数据。由于数据量较大,如下示例通过过滤仅显示 Lettuce 相关的指标数据。
