Spring学习笔记(二十九)——SpringBoot Actuator指标监控

66 篇文章 11 订阅

SpringBoot Actuator简介&使用

简介

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

依赖坐标

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

SpringBoot Actuator 1.x与2.x的不同
请添加图片描述

如何使用

  • 引入场景
  • 访问 http://localhost:8080/actuator/**
  • 暴露所有监控信息为HTTP
management:
  endpoints:
    enabled-by-default: true #暴露所有端点信息
    web:
      exposure:
        include: '*'  #以web方式暴露
  • 测试引入是否成功
http://localhost:8080/actuator/beans
http://localhost:8080/actuator/configprops
http://localhost:8080/actuator/metrics
http://localhost:8080/actuator/metrics/jvm.gc.pause
http://localhost:8080/actuator/endpointName/detailPath

Actuator Endpoint指标端点

1. 最常使用的端点

在这里插入图片描述
最常用的Endpoint

  • Health:监控状况
  • Metrics:运行时指标
  • Loggers:日志记录

2、Health Endpoint

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

访问信息路径:http://localhost:8080/actuator/health

重要的几点:

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

在这里插入图片描述

3. Metrics Endpoint

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

  • 通过Metrics对接多种监控系统
  • 简化核心Metrics开发
  • 添加自定义Metrics或者扩展已有Metrics

访问信息路径:http://localhost:8080/actuator/metrics
在这里插入图片描述

4. 管理Endpoints

  1. 开启与禁用Endpoints
  • 默认所有的Endpoint除了shutdown都是开启的。
  • 需要开启或者禁用某个Endpoint。配置模式为 management.endpoint.<endpointName>.enabled = true
management:
  endpoint:
    beans:
      enabled: true
  • 或者禁用所有的Endpoint然后手动开启指定的Endpoint
management:
  endpoints:
    enabled-by-default: false
  endpoint:
    beans:
      enabled: true
    health:
      enabled: true
  1. 暴露Endpoints
    支持的暴露方式
  • HTTP:默认只暴露health和info Endpoint
  • JMX:默认暴露所有Endpoint
  • 除了health和info,剩下的Endpoint都应该进行保护访问。如果引入SpringSecurity,则会默认配置安全访问
    在这里插入图片描述

开启Endpoints和暴露Endpoints可以做以下配置

# management 是所有actuator的配置
# management.endpoint.端点名.xxxx 对某个端点的具体配置
management:
  endpoints:
    #默认开启所有监控端点
    enabled-by-default: true
    web:
      exposure:
        # 以web方式暴露所有端点
        include: '*'

  endpoint:   #对某个端点的具体配置
    health:
      show-details: always
      enabled: true

    info:
      enabled: true

    beans:
      enabled: true

    metrics:
      enabled: true

定制 Endpoint端点

在开发中,如果需要自己定义指标端点用于监控某一项功能或者模块,我们就可以使用自己定制 Endpoint端点,来达到自定义数据统计和指标监控的效果。
尝试定制四类端点信息

  1. 定制 Health 信息
  2. 定制info信息
  3. 定制Metrics信息
  4. 定制Endpoint

目录结构如下
在这里插入图片描述

1. 定制 Health 信息

  1. yml配置显示详细信息
management:
    health:
      enabled: true
      show-details: always #总是显示详细信息。可显示每个模块的状态信息
  1. 自定义健康组件 MyComHealthIndicator.java
    MyComHealthIndicator其中HealthIndicator是固定写法,必须要有,myCom 是该健康组件的名字
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
/**
 * @author tao
 * @date 2021-08-25 23:09
 * 概要:自定义健康组件
 */

//将组件放在容器中,其中 myCom 是该健康组件的名字
@Component
public class MyComHealthIndicator extends AbstractHealthIndicator {
    /**
     * 真实的检查方法
     *
     * @param builder
     * @throws Exception
     */
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        //mongodb 获取连接进行测试
        Map<String, Object> map = new HashMap<>();
        //检查完成
        if (1 == 1) {
            //健康
            //builder.up();
            builder.status(Status.UP);
            map.put("count", 1);
            map.put("ms", 200);
        } else {
            //宕机
            builder.down();
            builder.status(Status.OUT_OF_SERVICE);
            map.put("err", "连接超时");
            map.put("ms", 5000);
        }
        builder.withDetail("code", 100).withDetails(map);
    }
}
  1. 测试结果
    访问路径:http://localhost:8080/actuator/health
    在这里插入图片描述

2. 定制info信息

常用两种方式
1、编写配置文件

#定制监控的info信息
info:
  appName: @project.name@
  version: 2.0.1
  #使用@@可以获取maven的pom文件值,需要在pom文件里面添加配置信息
  mavenProjectName: @project.artifactId@
  mavenProjectVersion: @project.version@

注意:
使用@@可以获取maven的pom文件值,需要在pom文件里面添加配置信息
但是如果使用@@表达式报错或者没有提示时,可能时因为pom.mxl中没有打开@@获取pom文件信息
需要如下操作:

  • <build>标签下加入以下配置
			<resources>
			   <resource>
			      <directory>src/main/resources</directory>
			      <filtering>true</filtering>
			   </resource>
			</resources>
  • <plugins>下加入以下配置
<!--允许使用@@获取pom文件信息-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <delimiters>
                        <delimiter>@</delimiter>
                    </delimiters>
                    <useDefaultDelimiters>false</useDefaultDelimiters>
                </configuration>
            </plugin>

启用配置后就OK了。
2. 编写InfoContributor.java配置类

import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tao
 * @date 2021-08-25 23:42
 * 概要:
 */
@Component
public class AppInfoContributor implements InfoContributor {
    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("msg", "你好");
        builder.withDetail("hello", "如我西沉");
        Map<String, Object> map = new HashMap<>();
        map.put("phoneNum", "1205529635");
        map.put("QQ", "1205529635");
        map.put("name", "Nick");
        builder.withDetails(map);
    }
}
  1. 测试结果
    访问路径:http://localhost:8080/actuator/info
    在这里插入图片描述

3. 定制Metrics信息

  1. SpringBoot支持自动适配的Metrics

Micrometer 为 Java 平台上的性能数据收集提供了一个通用的 API,它提供了多种度量指标类型(Timers、Guauges、Counters等),同时支持接入不同的监控系统,例如 Influxdb、Graphite、Prometheus 等。我们可以通过 Micrometer 收集 Java 性能数据,配合 Prometheus 监控系统实时获取数据,并最终在 Grafana 上展示出来,从而很容易实现应用的监控。

Micrometer 提供了如下几种不同类型的计量器:

  • 计数器(Counter): 表示收集的数据是按照某个趋势(增加/减少)一直变化的,也是最常用的一种计量器,例如接口请求总数、请求错误总数、队列数量变化等。
  • 计量仪(Gauge): 表示搜集的瞬时的数据,可以任意变化的,例如常用的 CPU Load、Mem 使用量、Network 使用量、实时在线人数统计等,
  • 计时器(Timer): 用来记录事件的持续时间,这个用的比较少。
  • 分布概要(Distribution summary): 用来记录事件的分布情况,表示一段时间范围内对数据进行采样,可以用于统计网络请求平均延迟、请求延迟占比等。

在SpringBoot集成的Actuator中,MeterRegistry提供的方法如下
在这里插入图片描述
2. 增加定制Metrics
场景: 在自己编写了一个查询所有用户的接口后,想统计这个接口被调用的次数,因此在Actuator增加一个定制的Metrics指标,来监控接口的使用情况。
步骤:

  • 定义一个计量器(Counter)
  • 在构造方法中传入MeterRegistry
  • 使用meterRegistry构造一个计量器(counter)
  • 使用计量器进行增加数据:counter.increment();

因此可以在Service层编写定制Metrics的逻辑。
实现代码如下:

/**
 * @author tao
 * @date 2021-08-16 22:33
 * 概要:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    private Counter counter;

    //在构造方法中传入MeterRegistry
    public UserServiceImpl(MeterRegistry meterRegistry) {
        counter = meterRegistry.counter("UserService.findAll.count");
    }

    @Override
    public List<User> findAll() {
        //增加数据
        counter.increment();
        return userMapper.selectList(null);
    }
}
  1. 测试效果
  • 访问路径:http://localhost:8080/actuator/metrics
    会发现多了一个指标
    在这里插入图片描述
    这个是定制的metrics
  • 可以访问:http://localhost:8080/actuator/metrics/UserService.findAll.count 拿到计量监控数据
    在这里插入图片描述
  • 调用几次接口后
    在这里插入图片描述

4. 自定义Endpoint

  1. 可以通过下面路径查看所有的Endpoint
    http://localhost:8080/actuator
    在这里插入图片描述
  2. 自定义Endpoint
    场景:开发ReadinessEndpoint来管理程序是否就绪,或者LivenessEndpoint来管理程序是否存活;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Map;

/**
 * @author tao
 * @date 2021-08-26 0:45
 * 概要:自定义监控端点
 */
@Component
@Endpoint(id = "myService")
public class MyServiceEndpoint {


    @ReadOperation
    public Map getDockerInfo() {
        return Collections.singletonMap("info", "docker started...");
    }

    @WriteOperation
    private void stopDocker() {
        System.out.println("docker stop....");
    }
}

注意:@Spring Boot会去扫描@EndPoint注解下的@ReadOperation, @WriteOperation, @DeleteOperation注解,分别对应生成Get/Post/Delete的Mapping。注解中有个produces参数,可以指定media type, 如:application/json等。
3. 测试效果
配置好自定义EndPoint后,查看:http://localhost:8080/actuator
会发现已经出现有自己配置的EndPoint端点
在这里插入图片描述

SpringBoot Actuator指标监控可视化

SpringBoot提供了一个开源的SpringBoot Actuator指标监控可视化项目,可以点击下面链接进行下载学习,也可以拿到我文章末尾的代码源码。
https://github.com/codecentric/spring-boot-admin

搭建指标监控可视化项目

  1. 建立新SpringBoot工程
  2. 导入下面两个坐标依赖就可以
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
  1. 更改配置文件
# 应用名称
spring.application.name=springboot-adminserver
# 应用服务 WEB 访问端口
server.port=8888
  1. 在启动类东添加注解@EnableAdminServer运行启动AdminServer
@SpringBootApplication
@EnableAdminServer
public class SpringbootAdminserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootAdminserverApplication.class, args);
    }

}
  1. 直接启动项目
  2. 访问 http://localhost:8888/就可以进入指标监控可视化页面
    在这里插入图片描述
  3. 需要在客户端那边配置上可视化项目的路径,才能获取到要监控项目的指标数据
spring:
  boot:
    admin:
      client:
        url: http://localhost:8888
        instance:
          prefer-ip: true #使用IP将可视化项目注册进来
  1. 注册好之后就可以看到有应用数据进入可视化面板

可视化监控指标展示

  1. 点击应用就可以进入监控数据面板
    在这里插入图片描述
  2. 可以看到将监控的数据都进行了可视化(包括自定义数据)
    在这里插入图片描述
  3. 也可以看到其他的一些信息
    在这里插入图片描述

源码下载

链接:https://pan.baidu.com/s/1ZWzb3dNo-YnInyBdjTXRqw
提取码:50ap

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot项目中,可以使用Actuator提供的监控功能来监控应用程序的运行状态。为了实现Vue的监控配置,可以按照以下步骤操作: 1. 配置Actuator:在Spring Boot项目中添加Actuator依赖,并在application.properties或application.yml文件中配置Actuator的端点和安全性等相关参数。 2. 配置CORS:由于Vue应用程序是通过浏览器访问的,因此需要在Spring Boot项目中配置CORS允许跨域访问。 3. 编写Vue组件:在Vue应用程序中编写一个组件,通过Axios等库调用Actuator的API获取监控数据,并将其展示在页面上。 4. 部署到同一服务器:为了避免CORS的问题,最好将Vue应用程序部署到与Spring Boot项目同一服务器上。 具体实现可以参考以下代码: 1. 配置Actuator: 在application.yml文件中添加如下配置: ```yaml management: endpoints: web: exposure: include: "*" endpoint: health: show-details: always security: enabled: false ``` 2. 配置CORS: 在Spring Boot项目中添加CORS配置类: ```java @Configuration public class CorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("*") .allowedHeaders("*"); } }; } } ``` 3. 编写Vue组件: ```vue <template> <div> <h2>Actuator监控信息</h2> <table> <thead> <tr> <th>指标</th> <th>值</th> </tr> </thead> <tbody> <tr v-for="(value, key) in metrics" :key="key"> <td>{{ key }}</td> <td>{{ value }}</td> </tr> </tbody> </table> </div> </template> <script> import axios from 'axios'; export default { data() { return { metrics: {}, }; }, created() { axios.get('/actuator/metrics').then((res) => { this.metrics = res.data; }).catch((err) => { console.error(err); }); }, }; </script> ``` 以上代码实现了一个简单的Vue组件,通过Axios库调用Actuator的/metrics端点获取监控数据,并将其展示在表格中。 4. 部署到同一服务器: 将Vue应用程序部署到与Spring Boot项目同一服务器上,并通过nginx等服务器软件配置反向代理,将Vue应用程序的请求转发到Spring Boot项目中。这样可以避免CORS的问题,同时提高了应用程序的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不愿意做鱼的小鲸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值