天天看点

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

​​SpringBoot自动装配原理​​​​SpringBoot的自定义Starter​​

Actuator(监控)

1. Actuator介绍

  通过前面的介绍我们明白了SpringBoot为什么能够很方便快捷的构建Web应用,那么应用部署上线后的健康问题怎么发现呢?在SpringBoot中给我们提供了Actuator来解决这个问题。

官网地址:https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html

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.

Spring Boot包括许多附加特性,可以帮助您在将应用程序投入生产时监视和管理应用程序。您可以选择使用HTTP端点或使用JMX来管理和监视应用程序。审计、运行状况和度量收集也可以自动应用于您的应用程序。

  使用Actuator我们需要添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>      
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

2.端点(Endpoints)

  执行器端点(endpoints)可用于监控应用及与应用进行交互,Spring Boot包含很多内置的端点,你也可以添加自己的。例如,health端点提供了应用的基本健康信息。

   每个端点都可以启用或禁用。这控制着端点是否被创建,并且它的bean是否存在于应用程序上下文中。要远程访问端点,还必须通过JMX或HTTP进行暴露,大部分应用选择HTTP,端点的ID映射到一个带​​

​/actuator​

​​前缀的URL。例如,health端点默认映射到​

​/actuator/health​

​。

注意:

  Spring Boot 2.0的端点基础路径由“/”调整到”/actuator”下,如:​​

​/info​

​​调整为​

​/actuator/info​

​ 可以通过以下配置改为和旧版本一致:

management.endpoints.web.base-path=/      

  默认在只放开了​

​health​

​​和​

​info​

​两个 Endpoint。

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

  如果要放开更多的Endpoint,我们需要配置如下信息

management.endpoints.web.exposure.include=*      

  以下是SpringBoot中提供的Endpoint。

ID 描述 默认启用
auditevents 显示当前应用程序的审计事件信息 Yes
beans 显示一个应用中​

​所有Spring Beans​

​的完整列表
Yes
conditions 显示​

​配置类和自动配置类​

​(configuration and auto-configuration classes)的状态及它们被应用或未被应用的原因
Yes
configprops 显示一个所有​

​@ConfigurationProperties​

​的集合列表
Yes
env 显示来自Spring的 ​

​ConfigurableEnvironment​

​的属性
Yes
flyway 显示数据库迁移路径,如果有的话 Yes
health 显示应用的​

​健康信息​

​(当使用一个未认证连接访问时显示一个简单的’status’,使用认证连接访问则显示全部信息详情)
Yes
info 显示任意的​

​应用信息​

Yes
liquibase 展示任何Liquibase数据库迁移路径,如果有的话 Yes
metrics 展示当前应用的​

​metrics​

​信息
Yes
mappings 显示一个所有​

​@RequestMapping​

​路径的集合列表
Yes
scheduledtasks 显示应用程序中的​

​计划任务​

Yes
sessions 允许从Spring会话支持的会话存储中检索和删除(retrieval and deletion)用户会话。使用Spring Session对反应性Web应用程序的支持时不可用。 Yes
shutdown 允许应用以优雅的方式关闭(默认情况下不启用) No
threaddump 执行一个线程dump Yes

  shutdown端点默认是关闭的,我们可以打开它

# 放开 shutdown 端点
management.endpoint.shutdown.enabled=true      

  ​

​shutdown​

​​只支持post方式提交,我们可以使用​

​POSTMAN​

​来提交或者使用IDEA中提供的工具来提交。

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

  如果使用web应用(Spring MVC, Spring WebFlux, 或者 Jersey),你还可以使用以下端点:

ID 描述 默认启用
heapdump 返回一个GZip压缩的​

​hprof​

​堆dump文件
Yes
jolokia 通过HTTP暴露​

​JMX beans​

​(当Jolokia在类路径上时,WebFlux不可用)
Yes
logfile 返回​

​日志文件内容​

​(如果设置了logging.file或logging.path属性的话),支持使用HTTP Range头接收日志文件内容的部分信息
Yes
prometheus 以可以被Prometheus服务器抓取的格式显示​

​metrics​

​信息
Yes

  现在我们看的​

​health​

​信息比较少,如果我们需要看更详细的信息,可以配置如下

# health 显示详情
management.endpoint.health.show-details=always      

  再访问测试

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

  这样一来​

​health​

​不仅仅可以监控SpringBoot本身的状态,还可以监控其他组件的信息,比如我们开启Redis服务。

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

  添加Redis的配置信息

# Redis的 host 信息
spring.redis.host=192.168.100.120      

  重启服务,查看 ​

​http://localhost:8080/actuator/health​

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

3.监控类型

  介绍几个监控中比较重要的类型

3.1 health

  显示的系统的健康信息,这个在上面的案例中讲解的比较多,不再赘述。

3.2 metrics

  metrics 端点用来返回当前应用的各类重要度量指标,比如内存信息,线程信息,垃圾回收信息等。如下:

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

各个指标信息的详细描述:

序号 参数 参数说明 是否监控 监控手段 重要度
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 当前打开句柄数 监控文件句柄使用率,超过阈值后报警 重要

如果要查看具体的度量信息的话,直接在访问地址后面加上度量信息即可:

http://localhost:8080/actuator/metrics/jvm.buffer.memory.used      
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

添加自定义的统计指标

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

  • gauge 计量器,最简单的度量类型,只有一个简单的返回值,他用来记录一些对象或者事物的瞬时值。
  • Counter 计数器 简单理解就是一种只增不减的计数器,它通常用于记录服务的请求数量,完成的任务数量,错误的发生数量
  • Timer 计时器 可以同时测量一个特定的代码逻辑块的调用(执行)速度和它的时间分布。简单来说,就是在调用结束的时间点记录整个调用块执行的总时间,适用于测量短时间执行的事件的耗时分布,例如消息队列消息的消费速率。
  • Summary 摘要)用于跟踪事件的分布。它类似于一个计时器,但更一般的情况是,它的大小并不一定是一段时间的测量值。在micrometer中,对应的类是DistributionSummary,它的用法有点像Timer,但是记录的值是需要直接指定,而不是通过测量一个任务的执行时间。

测试:

@RestController
public class UserController {

    static final Counter userCounter = Metrics.counter("user.counter.total","services","bobo");
    private Timer timer = Metrics.timer("user.test.timer","timer","timersample");
    private DistributionSummary summary = Metrics.summary("user.test.summary","summary","summarysample");

    @GetMapping("/hello")
    public String hello(){
        // Gauge
        Metrics.gauge("user.test.gauge",8);
        // Counter
        userCounter.increment(1);
        // timer
        timer.record(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        summary.record(2);
        summary.record(3);
        summary.record(4);
        return "Hello";
    }
}      

访问 http://localhost:8080/hello 这个请求后在看 metrics 信息

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

多出了我们自定义的度量信息。

3.3 loggers

  loggers是用来查看当前项目每个包的日志级别的。

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

默认的是info级别。

修改日志级别:

发送POST请求到 http://localhost:8080/actuator/loggers/[包路径]

请求参数为

{
    "configuredLevel":"DEBUG"
}      

通过POSTMAN来发送消息

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

然后再查看日志级别发现已经变动了

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

控制台也可以看到

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

3.4 info

  显示任意的应用信息。我们可以在 properties 中来定义

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

访问:http://localhost:8080/actuator/info

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

4.自定义Endpoint

  如果我们需要扩展Endpoint,这时我们可以自定义实现,我们可以在类的头部定义如下的注解

@Endpoint

@WebEndpoint

@ControllerEndpoint

@RestControllerEndpoint

@ServletEndpoint

  再给方法添加@ReadOperation,@ WritOperation或@DeleteOperation注释后,该方法将通过JMX自动公开,并且在Web应用程序中也通过HTTP公开。

于方法的注解有以下三种,分别对应get post delete 请求

Operation HTTP method
@ReadOperation GET
@WriteOperation POST
@DeleteOperation DELETE

案例:

/**
 * 自定义Endpoint
 */
@Component
@Endpoint(id = "sessions")
public class MyHealthEndPoint  {

    /**
    * @Selector 获取传递的参数
    */
    @ReadOperation
    public Info get(@Selector String name){
        return new Info(name,"18");
    }
}      
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

5.Actuator的两种监控形态

  • http
  • jmx [Java Management Extensions] Java管理扩展

放开jmx

# 放开 jmx 的 endpoint
management.endpoints.jmx.exposure.include=*
spring.jmx.enabled=true      

通过jdk中提供的jconsole来查看

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

6.监控系统

  SpringBoot可以收集监控数据,但是查看不是很方便,这时我们可以选择开源的监控系统来解决,比如Prometheus

  • 数据采集
  • 数据存储
  • 可视化

  Prometheus在可视化方面效果不是很好,可以使用grafana来实现

6.1 Prometheus

  先来安装Prometheus:官网:https://prometheus.io/download/ 然后通过wget命令来直接下载

wget      
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

然后配置Prometheus。

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!
- job_name: 'Prometheus'
    static_configs:
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    - targets: ['192.168.127.1:8080']
      labels:
        instance:      
  • job_name:任务名称
  • metrics_path: 指标路径
  • targets:实例地址/项目地址,可配置多个
  • scrape_interval: 多久采集一次
  • scrape_timeout: 采集超时时间

执行脚本启动应用

./prometheus --config.file=prometheus.yml      
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

访问应用: http://ip:9090

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

然后在我们的SpringBoot服务中添加 Prometheus的端点,先添加必要的依赖

<dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
        </dependency>      

然后就会有该端点信息

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

Prometheus服务器可以周期性的爬取这个endpoint来获取metrics数据,然后可以看到

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

6.2 Grafana

  可视化工具:https://grafana.com/grafana/download

通过wget命令下载

wget https://dl.grafana.com/oss/release/grafana-8.0.6-1.x86_64.rpm
sudo yum install      

启动命令

sudo service grafana-server start
sudo service      

访问的地址是 http://ip:3000 默认的帐号密码 admin/admin

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

登录进来后的页面

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

添加数据源:

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

添加Dashboards https://grafana.com/grafana/dashboards 搜索SpringBoot的 Dashboards

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

找到Dashboards的ID

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

然后导入即可

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

点击Load出现如下界面

SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!

然后就可以看到对应的监控数据了