1. 概述

应用在部署在生产环境下,我们还需要考虑应用的管理与监控。例如说,应用是否健康存活、应用的 JVM 监控信息、服务器的监控信息(CPU、内存、磁盘等等)。

如果我们为应用的管理与监控做相应的开发,是需要一定的成本的。幸运的是,在 Spring Boot 框架提供了一个非常重要的新组件 spring-boot-actuator 。其文档介绍如下:

FROM 《Spring Boot Actuator: Production-ready Features》

Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production.
Spring Boot 包含许多附加功能,可以帮助您在将应用程序推向生产环境时对其进行监视和管理。

You can choose to manage and monitor your application by using HTTP endpoints or with JMX. 您可以选择使用 HTTP 端点或 JMX 来管理和监视应用程序。

Auditing, health, and metrics gathering can also be automatically applied to your application.

审计(auditing)、健康状况(health)和指标(metrics)收集也可以自动应用到您的应用程序中。

可能对监控了解比较少的胖友,理解起来略微会有一点懵逼。简单的来说,Spring Boot Actuator 提供 HTTP API 接口,返回应用的审计(auditing)、健康状况(health)和指标(metrics)等数据。

让我们先来快速入门,一起来感受下。

2. 快速入门

本小节,我们来对 Actuator 做一个快速入门,以便我们对它有个直观的感受和认识。

2.1 引入依赖

在 pom.xml 文件中,引入相关依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><modelVersion>4.0.0</modelVersion><artifactId>lab-34-acturator-demo</artifactId><dependencies><!-- 实现对 Spring MVC 的自动化配置 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 实现对 Actuator 的自动化配置 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency></dependencies></project>
  • 另外,spring-boot-starter-web 依赖并不是必须的,仅仅是为了保证 Spring Boot 应用启动后持续运行。

2.2 配置文件

在 application.yml 中,添加 Actuator 配置,如下:

management:endpoints:# Actuator HTTP 配置项,对应 WebEndpointProperties 配置类web:base-path: /actuator # Actuator 提供的 API 接口的根目录。默认为 /actuatorexposure:include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。exclude: # 在 include 的基础上,需要排除的端点。通过设置 * ,可以排除所有端点。
  • 在 management.endpoints.web 配置项,设置 Actuator HTTP 配置项,对应 WebEndpointProperties 配置类。
  • Spring Boot 提供的 WebEndpointAutoConfiguration 自动化配置类,实现 Actuator HTTP 端点的配置。
  • 重点,Actuator 提供了多种端点( Endpoint ),可以通过配置来开启或关闭端点。这里,我们配置 include: '*' ,开启所有 Actuator 端点。

2.3 Application

创建 Application.java 类,配置 @SpringBootApplication 注解即可。代码如下:

// Application.java@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}

2.4 简单测试

打开浏览器,访问 http://127.0.0.1:8080/actuator/health 地址,获得应用的健康信息。响应结果如下:

{"status": "UP"
}
  • 表示应用处于开启状态。

打开浏览器,访问 http://127.0.0.1:8080/actuator/beans 地址,获得应用的所有 Spring Bean 信息。响应结果如下图:

至此,我们已经完成了对 Spring Boot Actuator 的快速入门。

3. 内置端点

在 org.springframework.boot.actuate 包下,我们可以看到 Actuator 已经和多个框架进行集成,提供内置端点。如下图所示:

在《Spring Boot Actuator: Production-ready Features》文档中,官方列举整理端点如下表格:

ID Description
auditevents Exposes audit events information for the current application. Requires an AuditEventRepository bean.
beans Displays a complete list of all the Spring beans in your application.
caches Exposes available caches.
conditions Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match.
configprops Displays a collated list of all @ConfigurationProperties.
env Exposes properties from Spring’s ConfigurableEnvironment.
flyway Shows any Flyway database migrations that have been applied. Requires one or more Flyway beans.
health Shows application health information.
httptrace Displays HTTP trace information (by default, the last 100 HTTP request-response exchanges). Requires an HttpTraceRepository bean.
info Displays arbitrary application info.
integrationgraph Shows the Spring Integration graph. Requires a dependency on spring-integration-core.
loggers Shows and modifies the configuration of loggers in the application.
liquibase Shows any Liquibase database migrations that have been applied. Requires one or more Liquibase beans.
metrics Shows ‘metrics’ information for the current application.
mappings Displays a collated list of all @RequestMapping paths.
scheduledtasks Displays the scheduled tasks in your application.
sessions Allows retrieval and deletion of user sessions from a Spring Session-backed session store. Requires a Servlet-based web application using Spring Session.
shutdown Lets the application be gracefully shutdown. Disabled by default.
threaddump Performs a thread dump.

下面,我们就逐个端点来瞅瞅,加深理解。

4. health 端点

health 端点,对应 GET /actuator/health 接口,对应 HealthEndpoint 类。

用于获取应用的健康状态。health 端点通过健康指示器 HealthIndicator ,获取不同的资源的健康信息。Actuator 内置了多个 HealthIndicator 实现,如下图所示:

  • DiskSpaceHealthIndicator ,基于磁盘空间的 HealthIndicator 实现类。默认配置下,剩余磁盘不足 10MB 时,则认为不健康。
  • PingHealthIndicator ,基于 Ping 的 HealthIndicator 实现类。因为能访问上 GET /actuator/health 接口,说明就是 Ping 的通,所以只返回健康。

当然,我们可以实现 HealthIndicator 接口,自定义自己的健康指示器。

在 health 端点中,一定定义了四种 Status 状态:

  • UP :可用。
  • DOWN :不可用。
  • OUT_OF_SERVICE :暂不提供服务,一般是开发者主动设置。可以认为是一种“特殊”的不可用。
  • UNKNOWN :未知状态。

下面,我们就来看看 health 端点的示例,同时编写一个自定义的 HealthIndicator 实现类。lab-34-actuator-demo 项目的基础上,复制出一个 lab-34-actuator-demo-health 项目

4.1 配置文件

修改 application.yml 配置,增加 health 端点的配置。配置如下:

management:endpoint:# Health 端点配置项,对应 HealthProperties 配置类health:enabled: true # 是否开启。默认为 true 开启。show-details: ALWAYS # 何时显示完整的健康信息。默认为 NEVER 都不展示。可选 WHEN_AUTHORIZED 当经过授权的用户;可选 ALWAYS 总是展示。status:http-mapping: # 设置不同健康状态对应的响应状态码DOWN: 503order: DOWN, OUT_OF_SERVICE, UP, UNKNOWN # 状态排序health:# DiskSpaceHealthIndicator 配置项,对应 DiskSpaceHealthIndicatorPropertiesdiskspace:enabled: true # 是否开启。默认为 true 开启。path: . # 目录。默认为 . 当前目录。threshold: # 剩余空间的阀值。默认为 10M 。endpoints:# Actuator HTTP 配置项,对应 WebEndpointProperties 配置类web:base-path: /actuator # Actuator 提供的 API 接口的根目录。默认为 /actuatorexposure:include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。exclude: # 在 include 的基础上,需要排除的端点。通过设置 * ,可以排除所有端点。

额外增加 management.endpoint.health 配置项,设置 health 端点的配置项,对应 HealthProperties 配置类。

  • Spring Boot 提供的 HealthEndpointAutoConfiguration 自动化配置类,实现 health 端点的配置。

  • enabled :是否开启。默认为 true 开启。虽然我们通过 management.endpoints.web.web.exposure.include = * 配置,开放所有端点,但是它仅仅是开放 health 端点的 HTTP ,实际还是需要配置 enabled = true 来开启 health 端点的功能。不过,因为 enabled 默认为 true ,所以也不需要主动去配置。

  • show-details :何时显示完整的健康信息。它一共有三种选择项 HealthProperties.Show:

    • NEVER :默认值,都不展示。这样,health 端点只会返回应用的汇总健康状态,不会包含完整的健康信息,正如我们在「2.4 简单测试」所看到的。
    • ALWAYS :总是展示。本示例我们采用该选择项,这样我们就可以看到每一个 HealthIndicator 提供的健康信息。
    • WHEN_AUTHORIZED :经过授权的用户,可看到完整的健康信息。
  • status.http-mapping :设置不同健康状态(status)对应的响应状态码。例如说,在我们配合 Tengine 的 健康检查功能 时,通过检测 health 端点,发现应用的健康状态为 DOWN 时,进行摘除。不过因为 Tengine 只能基于响应的状态码判断应用是否健康,所以我们需要将 DOWN 状态的应用,health 端点的返回 503 资源不可用。此时,我们就需要通过 status.http-mapping 来配置了。

    后来查询了下官方文档,默认情况下,UP 和 UNKNOWN 状态返回 200 响应码,DOWN 和 OUT_OF_SERVICE 返回 503 状态码(SERVICE_UNAVAILABLE) 。

    所以,这里我们也是无需配置的。

  • status.order :健康状态排序值。这里我们配置的 DOWN, OUT_OF_SERVICE, UP, UNKNOWN 就是默认的排序。因为多个 HealthIndicator 可能会返回不同的结果,最终需要汇总成一个健康状态。此时,以结果中按照 status.order 来排序之后,排在第一个的结果为汇总状态。我们可以在「4.3 简单测试」中,进一步理解。

  • 这里, management.endpoint.health 配置项。一般情况下,我们无需主动配置它,默认即可。

额外增加 management.health.diskspace 配置项,设置 DiskSpaceHealthIndicator 的配置项,对应 DiskSpaceHealthIndicatorProperties 配置类。

  • Spring Boot 提供的 DiskSpaceHealthContributorAutoConfiguration 自动化配置类,实现 DiskSpaceHealthIndicator 的配置。
  • enabled 属性:是否开启。默认为 true 开启。
  • path 属性:目录。默认为 . 当前目录。
  • threshold 属性:剩余空间的阀值。默认为 10M 。

4.2 DemoHealthIndicator

在本小节,我们自定义一个 HealthIndicator 实现类。在 cn.iocoder.springboot.lab34.actuatordemo.actuate 包下,创建 DemoHealthIndicator 类,继承 AbstractHealthIndicator 抽象类,示例 HealthIndicator 。代码如下:

// DemoHealthIndicator.java@Component
public class DemoHealthIndicator extends AbstractHealthIndicator {@Overrideprotected void doHealthCheck(Health.Builder builder) {// <1> 判断是否健康boolean success = checkSuccess();// <2> 如果健康,则标记状态为 UPif (success) {builder.up().build();return;}// <3> 如果不健康,则标记状态为 DOWNbuilder.down().withDetail("msg", "我就是做个示例而已");}private boolean checkSuccess() {return false;}}
  • AbstractHealthIndicator 是由 Actuator 提供的抽象基类,方便实现 HealthIndicator ,我们仅需实现 #doHealthCheck(Health.Builder builder) 方法即可。当然,内置的 HealthIndicator ,也是继承 AbstractHealthIndicator 抽象类。
  • 在类上,添加 @Component 注解,保证能够被 health 端点获取到。
  • <1> 处,调用 #checkSuccess() 方法,判断是否健康。这里因为是示例,我们先直接返回 false 。
  • <2> 处,如果健康,则调用 Health.Builder#up() 方法,标记健康状态为 Status.UP 。
  • <3> 处,如果不健康,则调用 Health.Builder#down() 方法,标记健康状态为 Status.DOWN 。同时,调用 Health.Builder#withDetail(String key, Object value) 方法,添加一组键值对,设置到详细信息中。

4.3 简单测试

① 第一轮

调用 Application#main(Object[] args) 方法,启动 Spring Boot 应用。

打开浏览器,访问 http://127.0.0.1:8080/actuator/health 地址,获得应用的健康信息。响应结果如下:

{"status": "DOWN","components": {"demo": {"status": "DOWN","details": {"msg": "我就是做个示例而已"}},"diskSpace": {"status": "UP","details": {"total": 499963174912,"free": 173201915904,"threshold": 10485760}},"ping": {"status": "UP"}}
}

因为我们配置了 management.endpoint.health.show-details=ALWAYS ,所以可以看到完整的健康信息。这里,展示了 3 个 HealthIndicator 的健康状态的结果:

  • "demo" 对应 DemoHealthIndicator ,因为我们在 #checkSuccess() 方法中强制返回了 false ,所以返回的健康状态就是 DOWN 。同时,我们也在 details 中看到了我们设置的 msg 键值对。
  • "diskSpace" 对应 DiskSpaceHealthIndicator ,返回的健康状态的结果是 UP 。同时,我们在 details 中可以看到 DiskSpaceHealthIndicator 设置的详细信息。
  • "ping" 对应 PingHealthIndicator ,返回的健康状态的结果是 UP 。因为 DiskSpaceHealthIndicator 没有设置详细信息,所以看不到 details 。

最终返回的健康状态是 DOWN 。我们回过头看下我们在 management.endpoint.health.status.order 的讲解。

  • 这里一共返回了 [UP, UP, DOWN] 三个健康状态,按照 management.endpoint.health.status.order 排序之后,结果是 [DOWN, UP, UP] 。
  • 取排序后的健康状态结果的第一个 DOWN ,成为最终的汇总状态进行返回。

上述的逻辑,通过 SimpleStatusAggregator 的 #getAggregateStatus(Set<Status> statuses) 来聚合。代码如下:

// SimpleStatusAggregator.javaprivate final List<String> order;private final Comparator<Status> comparator = new StatusComparator();@Override
public Status getAggregateStatus(Set<Status> statuses) {return statuses.stream().filter(this::contains) // <1>.sorted(this.comparator) // <2>.findFirst() // <3> .orElse(Status.UNKNOWN); // <4>
}
  • <1> 处,过滤掉多个 HealthIndicator 健康状态集合中,不包含在状态排序数组 order 的状态。
  • <2> 处,按照 comparator 进行排序。该 StatusComparator 排序器,基于状态排序数组 order 进行升序。
  • <3> 处,获得排序结果中的第一个状态。
  • <4> 处,如果因为 <1> 处过滤后的结果集合为空,则返回 Status.UNKNOWN 状态。

① 第二轮

修改 DemoHealthIndicator 的 #checkSuccess() 方法,强制返回 true 。然后,重启 Spring Boot 应用。

打开浏览器,访问 http://127.0.0.1:8080/actuator/health 地址,获得应用的健康信息。响应结果如下:

{"status": "UP","components": {"demo": {"status": "UP"},"diskSpace": {"status": "UP","details": {"total": 499963174912,"free": 174055534592,"threshold": 10485760}},"ping": {"status": "UP"}}
}

因为 3 个 HealthIndicator 的健康状态的结果都是 UP ,所以最终返回的健康状态也为 UP 。

5. info 端点

示例代码对应仓库:lab-34-actuator-demo-info 。

info 端点,对应 GET /actuator/info 接口,对应 InfoEndpoint 类。

用于获取应用的信息。info 端点通过信息贡献者 InfoContributor ,获取不同的来源的信息。Actuator 内置了多个 InfoContributor 实现,如下图所示:

当然,我们可以实现 InfoContributor 接口,自定义自己的信息贡献者。

下面,我们就来看看 info 端点的示例,同时编写一个自定义的 InfoContributor 实现类。考虑到不污染「2. 快速入门」 的示例,我们在 lab-34-actuator-demo 项目的基础上,复制出一个 lab-34-actuator-demo-info 项目。

项目监控之Spring Boot 监控端点 Actuator 入门相关推荐

  1. 如何做自己的服务监控?spring boot 2.x服务监控揭秘

    Actuator是spring boot项目中非常强大一个功能,有助于对应用程序进行监视和管理,通过 restful api请求来监管.审计.收集应用的运行情况,针对微服务而言它是必不可少的一个环节. ...

  2. Spring Boot 监控信息邮件报警通知

    在Spring Boot Admin Server中 进行设置 1.添加依赖 <dependency><groupId>org.springframework.boot< ...

  3. idea创建springboot项目+mybatis_从spring boot项目创建到netty项目过渡1

    本文要讲解三点 1 spring boot 项目创建 2 spring boot 项目基础上面创建netty项目(下一篇) 3 netty websocket支持wss以及配置负载均衡(下一篇) No ...

  4. java web jsp servlet项目如何转换为spring boot项目

    问题描述一:老项目jsp都是在WebContent目录下,servlet在web.xml中配置,而springboot项目这二个目录都不存在. 问题描述二.如何将已有javaweb项目改造为Sprin ...

  5. spring boot框架三分钟入门

    Spring Boot简介 什么是Spring Boot Spring Boot是由Pivotal团队提供的框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程. 该框架使用了特定的方式 ...

  6. Spring Boot(一)入门篇

    Spring Boot干货系列:(一)优雅的入门篇 前言 Spring一直是很火的一个开源框架,在过去的一段时间里,Spring Boot在社区中热度一直很高,所以决定花时间来了解和学习,为自己做技术 ...

  7. Spring Boot (16)---优雅的入门篇

    Spring Boot (16)---优雅的入门篇 Spring一直是很火的一个开源框架,在过去的一段时间里,Spring Boot在社区中热度一直很高,所以决定花时间来了解和学习,为自己做技术储备. ...

  8. Spring Boot 消息队列 RocketMQ 入门

    转载自  芋道 Spring Boot 消息队列 RocketMQ 入门 摘要: 原创出处 http://www.iocoder.cn/Spring-Boot/RocketMQ/ 「芋道源码」欢迎转载 ...

  9. Spring boot整合Redis(入门教程)

    目录 源码分析 jedis VS lettuce 整合测试 导入依赖 配置连接 测试 存入字符串 存入对象 五大数据类型操作 自定义RedisConfig 存入对象 Redis工具类(常用API) 以 ...

最新文章

  1. Dictionary解析json,里面的数组放进list,并绑定到DataGridView指定列
  2. 计算机视觉(AI)的算法有哪些,具体都有哪些特点?
  3. 目前我国家庭计算机用户接入因特网的下述,目前我国家庭计算机用户接入因特网的下述几种方法中,速度最快的是________ 。...
  4. mongo-mapreduce测试(4)——avg
  5. python文件之间的相互调用_用Python创建功能模块——截取字符串模块
  6. 牛客14392 猴子吃香蕉
  7. 带你一文看懂 Blockchain + NoSQL数据库
  8. 如何使mysql编码格式_Mysql设置编码方式及基本操作
  9. 第二阶段团队站立会议04
  10. python生成excel文件二维码_Python 根据excel内容批量生成二维码
  11. dell r710重装系统_DELL R710系统安装指南10页
  12. 人工智能ai下海百度云_云AI就像核电
  13. 计算机中二进制转十进制怎么算,二进制转十进制怎么算?二进制转十进制公式及方法!...
  14. 评价效率DEA方法原理
  15. Node.js阶段学习(一)
  16. 抖音拍摄脚本怎么写,掌握这几点快速拍摄爆款视频丨国仁网络资讯
  17. JSP (java服务器页面)
  18. 2021年美赛C题翻译、思路及感受
  19. 巡检报告实例-Python脚本生成
  20. python中能主动引发异常的是_python--异常处理-主动引发异常-自定义异常类

热门文章

  1. python实现钉钉机器人,发送自定义消息
  2. 深入掌握大数据Kafka的使用(基于Python开发)-张明阳-专题视频课程
  3. Android封闭系统,最封闭的Android系统—魅族Flyme
  4. Docker容器部署
  5. GUI编程基础01AWT(了解)
  6. LEAF:可学习的音频特征提取模块
  7. 计算机视觉在安防、交通、机器人、无人车等领域的应用
  8. 奖项 | 2019金塔奖名单公布!
  9. cad线性标注命令_CAD线性标注快捷键命令(教你如何标注滚轮尺寸)
  10. uniapp开发修改字体样式font-family