首页 > 编程笔记

Spring Boot Actuator应用监控组件

Spring Boot Actuator 通过 HTTP endpoints 或者 JMX 来管理和监控 Spring Boot 应用,如服务的审计、健康检查、指标统计和 HTTP追踪等。Spring Boot Actuator 同时还可以与 AppOptics、Datadog、Elastic、Influx、Prometheus 等第三方监控系统进行整合。完善的监控系统可以使业务系统更健壮。本文主要介绍 Spring Boot Actuator 的相关知识与实践应用。

Endpoints组件简介

Spring Boot Actuator Endpoints 可以让开发者监控或者动态地改变应用。Spring Boot Actuator 内置了一系列的端点,也可以自定义端点。默认情况下,Spring Boot Actuator 暴露了 health 和 info 两个端点。例如,访问 health 端点可以进行应用健康状态查询,如果应用健康,则返回 UP,如果不健康,则返回 DOWN。

通常情况下使用 HTTP 的方式访问端点信息,默认的访问路径是 /actuator。如果访问 health 端点,则使用 /actuator/health 即可。如表1 所示为 Spring Boot 提供的一些端点。

表1 Spring Boot提供的端点
Endpoint ID 说  明
auditevents 展示应用暴露的审计事件
beans 展示应用完整的Spring Beans列表
caches 暴露可用的caches
conditions 展示需要配置类的条件信息
configprops 配置属性集合
env 环境属性
flyway 数据库迁移路径信息
health 应用的健康状态
httptrace 最近100个HTTP请求的响应信息
info 应用的基本信息
integrationgraph 应用集成信息
loggers 应用的logger信息
metrics metrics统计信息
mappings @RequestMapping路径
scheduledtasks 定时任务信息
sessions session信息
shutdown 关闭应用
startup 启动信息
threaddump 线程信息

如果程序是 Web 应用,还可以使用下面的端点,如表 2 所示。

表2 Web应用可以使用的端点
Endpoint ID 说  明
heapdump 展示堆栈信息
jolokia 暴露JMX Beans信息
logfile 日志信息
prometheus Prometheus 抓取的metrics指标

默认情况下,除了 shutdown 端点之外,其他端点都是启用的。如果想要启用 shutdown 端点,可以通过配置 management.endpoint.<id>.enabled 属性来实现。具体配置如下:

management:
        endpoint:
          shutdown:
                enabled: true

如果想要禁用默认的端点,而只开启自己想要的端点,可以使用下面的配置:

management:
        endpoints:
          enabled-by-default: false
        endpoint:
          info:
            enabled: true

基于 HTTP 的方式默认暴露了 health 和 info 端点。如果想要暴露更多的端点,需要使用下面的配置:

management:
  endpoints:
    web:
      exposure:
        include: "*"
        exclude: "env,beans"

Spring Boot Actuator 端点的默认访问路径是 /actuator,如果想要修改该路径,需要进行如下配置:

management:
  endpoints:
    web:
      base-path: "/"
      path-mapping:
        health: "healthcheck"

同样可以修改访问的端口,配置信息如下:

management:
  server:
    port: 8081

如果想要修改端点的属性配置,可以进行如下修改:

management:
  endpoint:
    health:
      show-details: always

自定义端点

除了 Spring Boot Actuator 提供的通用端点之外,开发中还可以自定义端点。Spring Boot 提供了 @Endpoint 注解,带有 @Endpoint  注解的 Bean 即为自定义端点。@Jmx-Endpoint 和 @WebEndpoint 注解可分别通过 JMX 或者 HTTP 方式进行访问。

自定义端点提供了方法注解 @ReadOperation、@WriteOperation 和 @Delete-Operation,分别对应 HTTP 访问方法的 GET、POST 和 DELETE。下面自定义一个简单的端点,代码如下:
//自定义端点
@WebEndpoint(id="userEndpoint")
@Component
public class UserEndpoint {
    @ReadOperation
    public String readUserEndpoint(){
        return "test read userEndpoint!";
    }
    @WriteOperation
    public String writeUserEndpoint(){
        return "test write userEndpoint!";
    }
    @DeleteOperation
    public String deleteUserEndpoint(){
        return "test delete userEndpoint!";
    }
}
定义好端点 Bean 之后,需要暴露这个端点,配置信息如下:

management:
  endpoints:
    web:
      exposure:
        include: userEndpoint

访问 http://localhost:8080/actuator 即可看到 userEndpoint 端点已经暴露出来了。分别用 GET、POST 和 DELETE 方式访问http://localhost:8080/actuator/userEndpoint,将返回不同的信息。

优秀文章