还是要开心的,万一梦想真得实现了呢

上一章简单介绍了SpringBoot日志配置(四十七) , 如果没有看过,请观看上一章

Spring Boot Actuator 模块提供了生产级别的功能,比如健康检查,审计,指标收集,HTTP 跟踪等,

帮助我们监控和管理Spring Boot 应用。

老蝴蝶这里采用 Spring 2.X 版本的

一.集成 Actuator 的使用

在一个SpringBoot 可运行的老项目上 直接添加依赖

一.一 pom.xml 中添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

一.二 访问验证

在原先的访问基础上, 添加 /actuator 路径进行访问 (/actuator 是默认的访问路径)

如之前的访问路径是: http://localhost:8088/StockApi

那么访问网址: http://localhost:8088/StockApi/actuator

SpringBoot Actuator详解(四十八)_java

该页面会展示可以访问的路径信息, 如访问 /actuator/health

SpringBoot Actuator详解(四十八)_java_02

UP 表示服务是正常的, 状态为 200

/health /info 叫做 endpoint, 有很多种 endpoin

二. Actuator 详细讲解

二.一 Endpoints 介绍

Spring Boot 提供了所谓的 endpoints (下文翻译为端点)给外部来与应用程序进行访问和交互。

打比方来说,/health 端点 提供了关于应用健康情况的一些基础信息。metrics 端点提供了一些有用的应用程序指标(JVM 内存使用、系统CPU使用等)。

这些 Actuator 模块本来就有的端点我们称之为原生端点。根据端点的作用的话,我们大概可以分为三大类:

  • 应用配置类:获取应用程序中加载的应用配置、环境变量、自动化配置报告等与Spring Boot应用密切相关的配置类信息。
  • 度量指标类:获取应用程序运行过程中用于监控的度量指标,比如:内存信息、线程池信息、HTTP请求统计等。
  • 操作控制类:提供了对应用的关闭等操作类功能。

需要注意的就是:

  • 每一个端点都可以通过配置来单独禁用或者启动
  • 不同于Actuator 1.x,Actuator 2.x 的大多数端点默认被禁掉。 Actuator 2.x 中的默认端点增加了/actuator前缀。默认暴露的两个端点为/actuator/health/actuator/info

Actuator 提供的所有 endpoint:

HTTP方法

Endpoint

描述

GET

/actuator

查看有哪些 Actuator endpoint 是開放的

GET

/actuator/auditevent

查看 audit 的事件,例如認證進入、訂單失敗,需要搭配 Spring security 使用,sample code

GET

/actuator/beans

查看運行當下裡面全部的 bean,以及他們的關係

GET

/actuator/conditions

查看自動配置的結果,記錄哪些自動配置條件通過了,哪些沒通過

GET

/actuator/configprops

查看注入帶有 @ConfigurationProperties 類的 properties 值為何(包含默認值)

GET

/actuator/env (常用)

查看全部環境屬性,可以看到 SpringBoot 載入了哪些 properties,以及這些 properties 的值(但是會自動*掉帶有 key、password、secret 等關鍵字的 properties 的值,保護安全資訊)

GET

/actuator/flyway

查看 flyway DB 的 migration 資訊

GET

/actuator/health (常用)

查看當前 SpringBoot 運行的健康指標,值由 HealthIndicator 的實現類提供(所以可以自定義一些健康指標資訊,加到這裡面)

GET

/actuator/heapdump

取得 JVM 當下的 heap dump,會下載一個檔案

GET

/actuator/info

查看 properties 中 info 開頭的屬性的值,沒啥用

GET

/actuator/mappings

查看全部的 endpoint(包含 Actuator 的),以及他們和 Controller 的關係

GET

/actuator/metrics(常用)

查看有哪些指標可以看(ex: jvm.memory.max、system.cpu.usage),要再使用/actuator/metrics/{metric.name}分別查看各指標的詳細資訊

GET

/actuator/scheduledtasks

查看定時任務的資訊

POST

/actuator/shutdown

唯一一個需要 POST 請求的 endpoint,關閉這個 SpringBoot 程式

二.二 端点配置

上面是 Actuator 提供的所有的 endpoints, 可以通过配置, 进行选择的将这些功能曝露出来。

二.二.一 默认配置

Property

Default

management.endpoints.jmx.exposure.exclude

management.endpoints.jmx.exposure.include

*

management.endpoints.web.exposure.exclude

management.endpoints.web.exposure.include

info, healt

因為安全的因素,所以 Actuator 默認只會開放/actuator/health/actuator/info這兩個 endpoint,

如果要開放其他 endpoint 的話,需要額外在 application.yaml 中做設置。

我们可以通过以上配置,来配置通过JMX 和 HTTP 暴露的端点。

二.二.二 曝露配置

  1. 打开所有的监控点, 不包含 shutdown , 注意 * 要加上 双引号
management:
  endpoints:
    web:
      exposure:
        # 打开所有的监控点
        include: "*"

SpringBoot Actuator详解(四十八)_spring boot_03

  1. 除了原有的 health 和 info 外,再打开其他的,如 beans 和 mappings
management:
  endpoints:
    web:
      exposure:
        # 只打开特定的几个
        include: beans,mappings,health,info

SpringBoot Actuator详解(四十八)_spring_04

  1. exclude 排除某些
management:
  endpoints:
    web:
      exposure:
        # 排除 metrics,threaddump
        exclude: metrics,threaddump
        # 打开全部
        include: "*"

SpringBoot Actuator详解(四十八)_JVM_05

  1. 开放 shutdown
management:
  endpoints:
    web:
      exposure:
        # 打开全部
        include: "*"
  endpoint:
    shutdown:
      # 通过指定接口关闭 SpringBoot
      enabled: true

SpringBoot Actuator详解(四十八)_spring_06

二.二.三 路径映射

默认情况下所有端点都暴露在“/actuator”路径下 , 各种 endpoints 对应的 href 也是默认给定的。 这是可以改变的。

management:
  endpoints:
    web:
      exposure:
        # 打开全部
        include: "*"
      # 自定义监控路径 manage
      base-path: /manage
      path-mapping:
        # 修改某些 endpoint 的路径配置
        health: myhealth
  endpoint:
    shutdown:
      # 通过指定接口关闭 SpringBoot
      enabled: true

原先的路径是 404 了

SpringBoot Actuator详解(四十八)_spring boot_07

需要通过 /manage 进行访问

SpringBoot Actuator详解(四十八)_spring_08

其中观察到 health 的 href 也发生了改变

SpringBoot Actuator详解(四十八)_tomcat_09

二.二.四 管理端口调整

我们访问 /actuator 时, 并没有输入端口, 默认跟server.port一样,

我们可以指定端口, 可以防止被其他人猜到

management:
  server:
    port: 8089
  endpoints:
    web:
      exposure:
        # 打开全部
        include: "*"

通过 8088 端口访问的时候

SpringBoot Actuator详解(四十八)_tomcat_10

使用 8089 端口访问时,要 去掉 项目名

http://localhost:8089/actuator

SpringBoot Actuator详解(四十八)_spring boot_11

二.二.五 端点响应缓存

对于一些不带参数的端点请求会自动进行缓存,

我们可以通过如下方式配置缓存时间,下面配置表示 beans 端点的缓存时间为 100s

management:
  endpoints:
    web:
      exposure:
        # 打开全部
        include: "*"
  endpoint:
    beans:
      cache:
        time-to-live: 100s

二.三 重要端口解析

将个性化的配置都进行还原 (端口,默认路径等)

management:
  endpoints:
    web:
      exposure:
        # 打开全部
        include: "*"
  endpoint:
    beans:
      cache:
        time-to-live: 100s
#    health:
#      show-details: always
    shutdown:
      # 通过指定接口关闭 SpringBoot
      enabled: true

二.三.一 /health

health 配置

当我们开启health的健康端点时,我们能够查到应用健康信息是一个汇总的信息,

访问 http://localhost:8088/StockApi/actuator/health 时,我们获取到的信息是{"status":"UP"}

status的值还有可能是 DOWN。

SpringBoot Actuator详解(四十八)_java_12

要想查看详细的应用健康信息需要配置:

management.endpoint.health.show-details=always
management:
  endpoints:
    web:
      exposure:
        # 打开全部
        include: "*"
  endpoint:
    health:
      show-details: always
    shutdown:
      # 通过指定接口关闭 SpringBoot
      enabled: true

该属性可以使用以下值之一进行配置:

  1. never:不展示详细信息,up或者down的状态,默认配置
  2. when-authorized:详细信息将会展示给通过认证的用户。授权的角色可以通过management.endpoint.health.roles配置
  3. always:对所有用户暴露详细信息

SpringBoot Actuator详解(四十八)_spring boot_13

会进行 数据库, 磁盘, ping, redis 邮箱(如果有引用的话)等重要组件的检测。

/health端点有很多自动配置的健康指示器:如redis、rabbitmq、db等组件。

当你的项目有依赖对应组件的时候,这些健康指示器就会被自动装配,继而采集对应的信息。

当如上的组件有一个状态异常,应用服务的整体状态即为down。我们也可以通过配置禁用某个组件的健康监测。

management.health.mongo.enabled: false

或者禁用所有自动配置的健康指示器:

management.health.defaults.enabled: false

二.三.二 /metrics

  • 查看所有可追踪的度量

/metrics端点用来返回当前应用的各类重要度量指标,比如:内存信息、线程信息、垃圾回收信息、tomcat、数据库连接池等。

{
  "names": [
    "jvm.memory.max",
    "jvm.threads.states",
    "jvm.gc.memory.promoted",
    "jvm.memory.used",
    "jvm.gc.max.data.size",
    "jvm.gc.pause",
    "jvm.memory.committed",
    "system.cpu.count",
    "logback.events",
    "jvm.buffer.memory.used",
    "jvm.threads.daemon",
    "system.cpu.usage",
    "jvm.gc.memory.allocated",
    "jvm.threads.live",
    "jvm.threads.peak",
    "process.uptime",
    "process.cpu.usage",
    "jvm.classes.loaded",
    "jvm.classes.unloaded",
    "jvm.gc.live.data.size",
    "jvm.buffer.count",
    "jvm.buffer.total.capacity",
    "process.start.time"
  ]
}

SpringBoot Actuator详解(四十八)_JVM_14

各个指标说明如下:

序号

参数

参数说明

是否监控

监控手段

重要度

JVM

1

jvm.memory.max

JVM 最大内存

2

jvm.memory.committed

JVM 可用内存


展示并监控堆内存和 Metaspace

重要

3

jvm.memory.used

JVM 已用内存


展示并监控堆内存和 Metaspace

重要

4

jvm.buffer.memory.used

JVM 缓冲区已用内存

5

jvm.buffer.count

当前缓冲区数

6

jvm.threads.daemon

JVM 守护线程数


显示在监控页面

7

jvm.threads.live

JVM 当前活跃线程数


显示在监控页面;监控达到阈值时报警

重要

8

jvm.threads.peak

JVM 峰值线程数


显示在监控页面

9

jvm.classes.loaded

加载 classes 数

10

jvm.classes.unloaded

未加载的 classes 数

11

jvm.gc.memory.allocated

GC 时,年轻代分配的内存空间

12

jvm.gc.memory.promoted

GC 时,老年代分配的内存空间

13

jvm.gc.max.data.size

GC 时,老年代的最大内存空间

14

jvm.gc.live.data.size

FullGC 时,老年代的内存空间

15

jvm.gc.pause

GC 耗时


显示在监控页面

TOMCAT

16

tomcat.sessions.created

tomcat 已创建 session 数

17

tomcat.sessions.expired

tomcat 已过期 session 数

18

tomcat.sessions.active.current

tomcat 活跃 session 数

19

tomcat.sessions.active.max

tomcat 最多活跃 session 数


显示在监控页面,超过阈值可报警或者进行动态扩容

重要

20

tomcat.sessions.alive.max.second

tomcat 最多活跃 session 数持续时间

21

tomcat.sessions.rejected

超过 session 最大配置后,拒绝的 session 个数


显示在监控页面,方便分析问题

22

tomcat.global.error

错误总数


显示在监控页面,方便分析问题

23

tomcat.global.sent

发送的字节数

24

tomcat.global.request.max

request 最长时间

25

tomcat.global.request

全局 request 次数和时间

26

tomcat.global.received

全局 received 次数和时间

27

tomcat.servlet.request

servlet 的请求次数和时间

28

tomcat.servlet.error

servlet 发生错误总数

29

tomcat.servlet.request.max

servlet 请求最长时间

30

tomcat.threads.busy

tomcat 繁忙线程


显示在监控页面,据此检查是否有线程夯住

31

tomcat.threads.current

tomcat 当前线程数(包括守护线程)


显示在监控页面

重要

32

tomcat.threads.config.max

tomcat 配置的线程最大数


显示在监控页面

重要

33

tomcat.cache.access

tomcat 读取缓存次数

34

tomcat.cache.hit

tomcat 缓存命中次数

CPU

35

system.cpu.count

CPU 数量

36

system.load.average.1m

load average


超过阈值报警

重要

37

system.cpu.usage

系统 CPU 使用率

38

process.cpu.usage

当前进程 CPU 使用率


超过阈值报警

39

http.server.requests

http 请求调用情况


显示 10 个请求量最大,耗时最长的 URL;统计非 200 的请求量

重要

40

process.uptime

应用已运行时间


显示在监控页面

41

process.files.max

允许最大句柄数


配合当前打开句柄数使用

42

process.start.time

应用启动时间点


显示在监控页面

43

process.files.open

当前打开句柄数


监控文件句柄使用率,超过阈值后报警

重要

  • 查看某个度量的详细信息

不同于1.x,Actuator在这个界面看不到具体的指标信息,只是展示了一个指标列表。为了获取到某个指标的详细信息,我们可以请求具体的指标信息,像这样:

http://localhost:8088/StockApi/actuator/metrics/{name}

如查询 jvm.buffer.memory.used

http://localhost:8088/StockApi/actuator/metrics/jvm.buffer.memory.used

SpringBoot Actuator详解(四十八)_spring boot_15

除了使用 metrics 端点默认的这些统计指标外,我们还可以实现自定义统计指标。Metrics 提供 4 种基本的度量类型:Gauge、Counter、Timer、Summary

关于这些的用法,老蝴蝶直接就抄写原文档了。

1,Gauge(计量器)

Gauge(计量器)是最简单的度量类型,只有一个简单的返回值,他用来记录一些对象或者事物的瞬时值。

(1)假设我们在一个 Contoller 使用一个类型为 Gauge 的计数器来记录一个数值:

@RestController
public class HelloController { 
    @GetMapping("/hello")
    public void hello() {
        Metrics.gauge("user.test.gauge", 3);
    }
}

(2)通过 /actuator/metrics 接口可以看到我们自定义的这个指标:

SpringBoot Actuator详解(四十八)_tomcat_16

(3)假设我们访问了 /hello 接口后,再次通过 /actuator/metrics/user.test.gauge 这个自定义度量的消息信息,显示如下:

SpringBoot Actuator详解(四十八)_spring boot_17

2,Counter(计数器)

Counter(计数器)简单理解就是一种只增不减的计数器。它通常用于记录服务的请求数量、完成的任务数量、错误的发生数量等等。

(1)为方便使用首先我们自定义一个计数器服务:

@Service
public class MyCounterService {
    static final Counter userCounter = Metrics.counter("user.counter.total", "services", "demo"); 
    public void processCollectResult() {
        userCounter.increment(1D);
    }
}

(2)然后增加一个 controller,触发这个服务:

@RestController
public class HelloController {
 
    @Autowired
    MyCounterService myCounterService;
 
    @GetMapping("/hello")
    public void hello() {
        myCounterService.processCollectResult();
    }
}

(3)通过 /actuator/metrics 接口可以看到我们自定义的这个指标:

SpringBoot Actuator详解(四十八)_spring boot_18

(4)假设我们访问了 3 次 /hello 接口,再次通过 /actuator/metrics/user.counter.total 这个自定义度量的消息信息,显示如下:

SpringBoot Actuator详解(四十八)_spring boot_19

3,Timer(计时器)

Timer(计时器)可以同时测量一个特定的代码逻辑块的调用(执行)速度和它的时间分布。

简单来说,就是在调用结束的时间点记录整个调用块执行的总时间,适用于测量短时间执行的事件的耗时分布,例如消息队列消息的消费速率。

(1)假设我们在一个 Contoller 使用 Timer 来记录某个方法的执行时长:

注意:在实际生产环境中,可以通过 spring-aop 把记录方法耗时的逻辑抽象到一个切面中,这样就能减少不必要的冗余的模板代码。

@RestController
public class HelloController {
 
    private Timer timer = Metrics.timer("user.test.timer","timer", "timersample");
 
    @GetMapping("/hello")
    public void hello() {
 
        // 执行createOrder方法并记录执行时间
        timer.record(() -> createOrder());
    }
 
    //模拟方法耗时
    private void createOrder() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
        }
    }
}

(2)假设我们访问了 3 次 /hello 接口,再次通过 /actuator/metrics/user.test.timer 这个自定义度量的消息信息,显示如下:

SpringBoot Actuator详解(四十八)_spring boot_20

4,Summary(摘要)

Summary(摘要)用于跟踪事件的分布。它类似于一个计时器,但更一般的情况是,它的大小并不一定是一段时间的测量值。

在 micrometer 中,对应的类是 DistributionSummary,它的用法有点像 Timer,但是记录的值是需要直接指定,而不是通过测量一个任务的执行时间。

(1)假设我们在一个 Contoller 使用 Summary 来连续记录三次值:

@RestController
public class HelloController {
 
    private DistributionSummary summary = Metrics.summary("user.test.summary","summary", "summarysample");
 
    @GetMapping("/hello")
    public void hello() {
        summary.record(2D);
        summary.record(3D);
        summary.record(4D);
    }
}

(2)假设我们访问 /hello 接口后,再次通过 /actuator/metrics/user.test.summary 这个自定义度量的消息信息,显示如下:

SpringBoot Actuator详解(四十八)_tomcat_21

二.三.三 /info

/info端点可以用来展示应用信息,主要包含三大类:自定义信息、Git 信息、以及项目构建信息。

http://localhost:8088/StockApi/actuator/info

原配置查询:

SpringBoot Actuator详解(四十八)_java_22

可以进行自定义配置

## 描述项目基础信息
info:
  app:
    name: StockTool
    port: Xxxx
    version: 2.0.0
    author: 岳泽霖

SpringBoot Actuator详解(四十八)_java_23

二.三.四 /beans

/beans端点会返回Spring 容器中所有bean的别名、类型、是否单例、依赖等信息。

http://localhost:8088/StockApi/actuator/beans

SpringBoot Actuator详解(四十八)_tomcat_24

二.三.五 /heapdump

会自动生成一个 Jvm 的堆文件 heapdump, 可以查看内存快照

http://localhost:8088/StockApi/actuator/heapdump

二.三.六 /threaddump

方便我们在日常定位问题的时候查看线程的情况。 主要展示了线程名、线程ID、线程的状态、是否等待锁资源、线程堆栈等信息。就是可能查看起来不太直观

http://localhost:8088/StockApi/actuator/threaddump

SpringBoot Actuator详解(四十八)_tomcat_25

二.三.七 /loggers

  • 查看日志等级

/loggers 端点暴露了我们程序内部配置的所有logger的信息

http://localhost:8088/StockApi/actuator/loggers

SpringBoot Actuator详解(四十八)_spring_26

可以单独访问某个类的日志情况

name 为 包名 或者具体的类全限定名称

http://localhost:8088/StockApi/actuator/loggers/{name}

SpringBoot Actuator详解(四十八)_spring_27

SpringBoot Actuator详解(四十八)_spring_28

  • 改变运行时日志等级

/loggers端点能够动态修改你的日志等级。

url 为 要修改的路径

SpringBoot Actuator详解(四十八)_JVM_29

{
  "configuredLevel": "DEBUG"
}

修改成 DEBUG 级别

SpringBoot Actuator详解(四十八)_spring boot_30

二.三.八 /shutdown 关闭

属于操作控制类端点,可以优雅关闭 Spring Boot 应用。要使用这个功能首先需要在配置文件中开启

management.endpoint.shutdown.enabled=true
management:
  endpoints:
    web:
      exposure:
        # 打开全部
        include: "*"
  endpoint:
    health:
      show-details: always
    shutdown:
      # 通过指定接口关闭 SpringBoot
      enabled: true

目前程序还在启动中, 在 ApiFox 中执行应用

SpringBoot Actuator详解(四十八)_tomcat_31

在 idea 中, 应用也确实关闭了。




谢谢您的观看,如果喜欢,请关注我,再次感谢 !!!