第八课 SpringBoot2基础-指标监控

第八课 SpringBoot2基础-指标监控,第1张

第八课 SpringBoot2基础-指标监控 第八课 SpringBoot2基础-指标监控

tags:

  • Spring Boot
  • 2021尚硅谷
  • 雷丰阳

文章目录
  • 第八课 SpringBoot2基础-指标监控
    • 第一节 SpringBoot Actuator简介
    • 第二节 Actuator端点
      • 2.1 最常使用的端点介绍
      • 2.2 Health Endpoint
      • 2.3 Metrics Endpoint
      • 2.4 管理Endpoints
    • 第三节 定制 Endpoint
      • 3.1 定制 Health 信息
      • 3.2 定制info信息
      • 3.3 定制Metrics信息
      • 3.4 定制Endpoint
    • 第四节 可视化界面

第一节 SpringBoot Actuator简介
  1. 未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot就抽取了Actuator场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。
        
            org.springframework.boot
            spring-boot-starter-actuator
                
  1. SpringBoot Actuator1.x与2.x有所不同
  2. 看下依赖包, 发现micrometer这个包。是用来我们自定义监控指标的包。
  3. 使用方法:
    • 引入场景
    • http://localhost:8080/actuator @Override protected void doHealthCheck(Health.Builder builder) throws Exception { // mongodb 获取链接进行测试 Map map = new HashMap<>(); if (1 == 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("timeout", 3000); } builder.withDetail("code", 100) .withDetails(map); } }
      1. http://localhost:8080/actuator/health
      2. 还可以实现接口。
      import org.springframework.boot.actuate.health.Health;
      import org.springframework.boot.actuate.health.HealthIndicator;
      import org.springframework.stereotype.Component;
      
      @Component
      public class MyHealthIndicator implements HealthIndicator {
      
          @Override
          public Health health() {
              int errorCode = check(); // perform some specific health check
              if (errorCode != 0) {
                  return Health.down().withDetail("Error Code", errorCode).build();
              }
              return Health.up().build();
          }
      
      }
      
      // 构建Health
      Health build = Health.down()
                      .withDetail("msg", "error service")
                      .withDetail("code", "500")
                      .withException(new RuntimeException())
                      .build();
      
      3.2 定制info信息
      1. 第一种方法:编写配置文件
      info:
        appName: boot-admin
        version: 2.0.1
        mavenProjectName: @project.artifactId@  #使用@@可以获取maven的pom文件值
        mavenProjectVersion: @project.version@
      
      1. 第二种方法:编写InfoContributor
      package com.atguigu.acutuator.info;
      
      import java.util.Collections;
      
      import org.springframework.boot.actuate.info.Info;
      import org.springframework.boot.actuate.info.InfoContributor;
      import org.springframework.stereotype.Component;
      
      @Component
      public class AppInfoInfoContributor implements InfoContributor {
      
          @Override
          public void contribute(Info.Builder builder) {
              builder.withDetail("msg", "你好")
                     .withDetail("hello", "niupi")
                     .withDetails(Collections.singletonMap("key", "value"));
          }
      
      }
      
      1. 如果同时用上面方法,返回的是合并后的info.
      2. http://localhost:8080/actuator/info
      3.3 定制Metrics信息
      1. 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 metrics
      2. 增加定制Metrics。比如实现某个接口调用次数指标的获取。
      package com.atguigu.service.impl;
      
      import com.atguigu.bean.City;
      import com.atguigu.mapper.CityMapper;
      import com.atguigu.service.CityService;
      import io.micrometer.core.instrument.Counter;
      import io.micrometer.core.instrument.MeterRegistry;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      
      @Service
      public class CityServiceImpl implements CityService {
      
           @Autowired
           CityMapper cityMapper;
      
           Counter counter;
      
           // 构造器注入方式
           public CityServiceImpl(MeterRegistry meterRegistry){
                // 把指标cityService.saveCity.count注册进来
                Counter counter = meterRegistry.counter("cityService.saveCity.count");
           }
      
           public City getById(Long id){
                return cityMapper.getById(id);
           }
      
           public void saveCity(City city){
          	// 计数
                counter.increment();
                cityMapper.insert(city);
           }
      
      }
      
      1. http://localhost:8080/actuator/metrics
      2. http://localhost:8080/actuator/metrics/cityService.saveCity.count
      3. 也可以使用下面方法定制Metrics。
      //也可以使用下面的方式
      @Bean
      MeterBinder queueSize(Queue queue) {
          return (registry) -> Gauge.builder("queueSize", queue::size).register(registry);
      }
      
      3.4 定制Endpoint
      package com.atguigu.acutuator.endpoint;
      
      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;
      
      @Component
      @Endpoint(id = "myservice") // 端点的名字
      public class MyServiceEndPoint {
          // 这个注解代表端点的读信息 http://localhost:8080/actuator/myservice
          @ReadOperation
          public Map getDockerInfo(){
              return Collections.singletonMap("info","docker started...");
          }
      
          // 这个注解代表端点的写 *** 作
          @WriteOperation
          private void restartDocker(){
              System.out.println("docker restarted....");
          }
      }
      
      1. 场景:开发ReadinessEndpoint来管理程序是否就绪,或者LivenessEndpoint来管理程序是否存活;
      2. 当然,这个也可以直接使用 https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-kubernetes-probes
      第四节 可视化界面
      1. https://github.com/codecentric/spring-boot-admin
      2. 按照说明搭建一个spring-boot-admin可视化服务器。
      3. 代码中配置服务端依赖。
        
          de.codecentric
          spring-boot-admin-starter-client
          2.3.1
        
      
      1. 代码中配置服务端
        boot:
          admin:
            client:
              url: http://127.0.0.1:8888
              instance:
                prefer-ip: true # 修改监控中注册的域名为ip
        application:
          name: boot-05-web-admin # 修改监控中注册的应用名
      
      1. 先运行服务端,在运行客户端。

      欢迎分享,转载请注明来源:内存溢出

      原文地址:https://54852.com/zaji/5081846.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-16
下一篇2022-11-16

发表评论

登录后才能评论

评论列表(0条)

    保存