使用 Actuator 监控 Spring Boot 应用
背景
我们都知道 Spring Boot 是一个用于快速开发 Java 的框架,不需要太多的配置即可使用 Spring 的大量功能。Spring Boot 遵循着“约定大于配置”的原则,许多功能使用默认的配置即可。这样的做法好处在于我们不需要像使用 Spring 那 样编写一大堆的XML配置代码,但过于简单的配置过程会让我们在了解各种依赖,配置之间的关系过程上带来一些困难。不过没关系,在 Spring Boot 中,我们可 以使用 Actuator 来监控应用,Actuator 提供了一系列的 RESTful API 让我们可以更为细致的了解各种信息。
未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot 就抽取了 Actuator 场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。
Spring Boot Actuator 简介
Spring Boot Actuator 可以帮助你监控和管理 Spring Boot 应用,比如健康检查、审计、统计和 HTTP 追踪等。所有的这些特性可以通过 JMX 或者 HTTP endpoints 来获得。
Spring Boot Actuator 同 时 还 可 以 与 外 部 应 用 监 控 系 统 整 合 , 比 如 Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic 等。这些 系统提供了非常好的仪表盘、图标、分析和告警等功能,使得你可以通过统一的接口轻松的监控和管理你的应用。
Actuator 使用 Micrometer 来整合上面提到的外部应用监控系统。这使得只要通过非常小的配置就可以集成任何应用监控系统。
如何使用
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
启动项目
访问 http://localhost:8080/actuator/
1) http://localhost:8080/actuator/beans
2) http://localhost:8080/actuator/configprops
3) http://localhost:8080/actuator/metrics
4) http://localhost:8080/actuator/metrics/jvm.gc.pause
5) http://localhost:8080/actuator/endpointName/detailPath
测试效果
Actuator Endpoint
最常使用的端点
如果您的应用程序是 Web 应用程序(Spring MVC,Spring WebFlux 或 Jersey), 则可以使用以下附加端点
Health Endpoint
健康检查端点,我们一般用于在云平台,平台会定时的检查应用的健康状况,我们就需要 Health Endpoint 可以为平台返回当前应用的一系列组件健康状况的集合。重要的几点:
1) health endpoint 返回的结果,应该是一系列健康检查后的一个汇总报告
2) 很多的健康检查默认已经自动配置好了,比如:数据库、redis 等
3) 可以很容易的添加自定义的健康检查机制
管理 Endpoints
1) 开启与禁用 Endpoints 默认所有的 Endpoint 除过 shutdown 都是开启的。 需要开启或者禁用某个 Endpoint。配置模式为
management:
endpoints:
enabled-by-default: true
2) 暴露 Endpoints
支持的暴露方式: JMX:默认暴露所有 Endpoint; HTTP:默认只暴露 health 和 info Endpoint。除过 health 和 info,剩下的 Endpoint 都应该进行保护访问。如果引入 Spring Security,则会默认配置安全访问规则配置方式为
management:
endpoints:
enabled-by-default: true
web:
exposure:
include: '*'
3) 启动项目,访问 http://localhost:8080/actuator/