# 指标监控

Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application.

https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html#actuator

未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot就抽取了Actuator场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
1
2
3
4

# 1.x与2.x的不同

# 使用

Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. For example, the health endpoint provides basic application health information.

Each individual endpoint can be enabled or disabled (opens new window) and exposed (made remotely accessible) over HTTP or JMX (opens new window). An endpoint is considered to be available when it is both enabled and exposed. The built-in endpoints will only be auto-configured when they are available. Most applications choose exposure via HTTP, where the ID of the endpoint along with a prefix of /actuator is mapped to a URL. For example, by default, the health endpoint is mapped to /actuator/health.

当我们就starter导入启动web程序的时候,那么我们就可以通过通过网址http://localhost:8080//actuator/进行访问,但是默认值开启health,其他的功能,我们需要开启

我们可以通过两种方式来监控程序

  • 通过jmx

    在cmd中输入jconsole便可以进行监控

  • 通过web,也就是通过发送请求的方式,像这种方式就是HTTP的监控http://localhost:8080//actuator/

可以查看网址

https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html#actuator.endpoints.enabling

ID 描述
auditevents 暴露当前应用程序的审核事件信息。需要一个AuditEventRepository组件
beans 显示应用程序中所有Spring Bean的完整列表。
caches 暴露可用的缓存。
conditions 显示自动配置的所有条件信息,包括匹配或不匹配的原因。
configprops 显示所有@ConfigurationProperties
env 暴露Spring的属性ConfigurableEnvironment
flyway 显示已应用的所有Flyway数据库迁移。 需要一个或多个Flyway组件。
health 显示应用程序运行状况信息。
httptrace 显示HTTP跟踪信息(默认情况下,最近100个HTTP请求-响应)。需要一个HttpTraceRepository组件。
info 显示应用程序信息。
integrationgraph 显示Spring integrationgraph 。需要依赖spring-integration-core
loggers 显示和修改应用程序中日志的配置。
liquibase 显示已应用的所有Liquibase数据库迁移。需要一个或多个Liquibase组件。
metrics 显示当前应用程序的“指标”信息。
mappings 显示所有@RequestMapping路径列表。
scheduledtasks 显示应用程序中的计划任务。
sessions 允许从Spring Session支持的会话存储中检索和删除用户会话。需要使用Spring Session的基于Servlet的Web应用程序。
shutdown 使应用程序正常关闭。默认禁用。
startup 显示由ApplicationStartup收集的启动步骤数据。需要使用SpringApplication进行配置BufferingApplicationStartup
threaddump 执行线程转储。

如果您的应用程序是Web应用程序(Spring MVC,Spring WebFlux或Jersey),则可以使用以下附加端点:

ID 描述
heapdump 返回hprof堆转储文件。
jolokia 通过HTTP暴露JMX bean(需要引入Jolokia,不适用于WebFlux)。需要引入依赖jolokia-core
logfile 返回日志文件的内容(如果已设置logging.file.namelogging.file.path属性)。支持使用HTTPRange标头来检索部分日志文件的内容。
prometheus 以Prometheus服务器可以抓取的格式公开指标。需要依赖micrometer-registry-prometheus

最常用的Endpoint

  • Health:监控状况

  • Metrics:运行时指标

  • Loggers:日志记录

# 配置

Spring Boot Actuator的所有配置都是以management作为前缀

# Exposing Endpoints

因为暴露端点是非常危险的,所以对于使用web进行监控,默认是暴露了health这个端点,也就是我们只有http://localhost:8080/actuator/health可以成功访问

ID JMX Web
auditevents Yes No
beans Yes No
caches Yes No
conditions Yes No
configprops Yes No
env Yes No
flyway Yes No
health Yes Yes
heapdump N/A No
httptrace Yes No
info Yes No
integrationgraph Yes No
jolokia N/A No
logfile N/A No
loggers Yes No
liquibase Yes No
metrics Yes No
mappings Yes No
prometheus N/A No
quartz Yes No
scheduledtasks Yes No
sessions Yes No
shutdown Yes No
startup Yes No
threaddump Yes No

# 暴露所有端点

management:
  endpoints:
    web:
      exposure:
        include: "*"
1
2
3
4
5

其中,*表示所有

management:
  endpoints:
    web:
      exposure:
        include: "*"
        exclude: "env,beans"
        暴露除了env,beans之外的所有端点
1
2
3
4
5
6
7

# 实例

# 查看自动配置信息

  • http://localhost:8080/actuator/conditions

    查看当前应用自动配置的信息

# 当前配置信息

http://localhost:8080/actuator/configprops

通过configprops可以查看,我们当前程序中的配置信息,也就是和配置文件绑定的那些配置

尽管有些我们没有给值,但是也是有默认值

# 环境监控

http://localhost:8080/actuator/env

这个就是我们当前的环境

包括java环境等等

# Health Endpoint

健康检查端点,我们一般用于在云平台,平台会定时的检查应用的健康状况,我们就需要Health Endpoint可以为平台返回当前应用的一系列组件健康状况的集合。

重要的几点:

  • health endpoint返回的结果,应该是一系列健康检查后的一个汇总报告
  • 很多的健康检查默认已经自动配置好了,比如:数据库、redis等
  • 可以很容易的添加自定义的健康检查机制

但是默认没有详细信息,我们可以通过配置文件进行开启

因为这些端点我们不能全部暴露,我们额可以只暴露几个

management:
  endpoints: # 对所有的端点控制
    web:
      exposure:
        include: "*"
    enabled-by-default: false
  #        exclude: "env,beans"
  endpoint: # 对单个端点控制
    health:
      show-details: always
      enabled: true

    metrics:
      enabled: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14

如果想对某个单个端点控制的话,那么可以使用management.endpoint.端点名.项方式

当对health端点开启详细后,我们就可以看到详细的数据

只有所有的值,都是UP时,才会返回UP,否则会返回宕机状态,通过这个,我们可以多长时间发送一个请求,如果是宕机,又重新自动部署等

# Metrics Endpoint

提供详细的、层级的、空间指标信息,这些信息可以被pull(主动推送)或者push(被动获取)方式得到;

  • 通过Metrics对接多种监控系统

  • 简化核心Metrics开发

  • 添加自定义Metrics或者扩展已有Metrics

http://localhost:8080/actuator/metrics可以通过此进行监控

如果想得到上面这些的具体值,那么就http://localhost:8080/actuator/metrics/http.server.requests就可以

# 定制endpoint

我们也可以定制端点

# 定制health信息

如果要定制health的话,那么我们就需要实现HealthIndicator接口

public abstract class AbstractHealthIndicator implements HealthIndicator {}

类的名字以名字+HealthIndicator进行命名,展示的时候,会去掉后面的HealthIndicator

@Component
public class MyComHealthIndicator extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck (Health.Builder builder) throws Exception {
        Map<String,Object> map = new HashMap<>();
        int i = 1;
        if (i == 1) {
            //健康
            //builder.up();
            builder.status(Status.UP);
            map.put("count",1);
            map.put("ms",100);

        }else {
            //不健康
            //builder.down();
            builder.status(Status.OUT_OF_SERVICE);
            map.put("err","连接超时");
            map.put("ms",3000);
        }
        builder.withDetail("map",map)
                .withDetail("ccc","fff");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 定制info信息

# 配置文件方式

如果使用yaml,比如要像下面这样写,info就是最高的节点,其并不是在management.endpoint.info,而是info

info:
  appName: chuchen
  version: 1.2.2
  maven1: @project.groupId@
1
2
3
4

但是如果关闭了所有的端点,就需要先开启info

management:
  endpoints:
    web:
      exposure:
        include: "*"
    enabled-by-default: false
  endpoint:
    info:
      enabled: true

info:
  appName: chuchen
  version: 1.2.2
  maven1: @project.groupId@
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 类方式

使用类方式,只需要实现InfoContributor接口就可以

@Component
public class MyInfo implements InfoContributor {

    @Override
    public void contribute (Info.Builder builder) {
        builder.withDetail("age",21)
                .withDetail("name","qsyyke")
                .withDetail("qq",2291308094l);
    }
}
1
2
3
4
5
6
7
8
9
10

他们可以混合使用,追加的方式

# 定制Metrics信息

# SpringBoot支持自动适配的Metrics

  • JVM metrics, report utilization of:
  • Various memory and buffer pools
  • Statistics related to garbage collection
  • Threads utilization
  • Number of classes loaded/unloaded
  • CPU metrics
  • File descriptor metrics
  • Kafka consumer and producer metrics
  • Log4j2 metrics: record the number of events logged to Log4j2 at each level
  • Logback metrics: record the number of events logged to Logback at each level
  • Uptime metrics: report a gauge for uptime and a fixed gauge representing the application’s absolute start time
  • Tomcat metrics (server.tomcat.mbeanregistry.enabled must be set to true for all Tomcat metrics to be registered)
  • Spring Integration (opens new window) metrics
@Component
public class MyMetrics {
    public MyMetrics (MeterRegistry meterRegistry) {
        Counter counter = meterRegistry.counter("myMetrics.method.running.counter");
    }
}
1
2
3
4
5
6

# 添加endpoint

我们也可以添加端点

@Endpoint(id = "myEndpoint")
@Component
public class MyEndpoint {

    @ReadOperation
    public Map<String,Object> getInfo() {
        return Collections.singletonMap("info","ReadOperation-------");
    }

    @WriteOperation
    public void restart() {
        System.out.println("chuhen----------");
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

尽管我们已经关闭端点暴露,但是我们自己的端点,可以不用去开启

# 可视化

https://github.com/codecentric/spring-boot-admin

首先,需要安装一个服务器,导入下面依赖,需要重新新建一个module

启动效果