21. Indicator monitoring


[Shang Silicon Valley] SpringBoot2 Zero-Basic Introductory Tutorial - Lecturer: Lei Fengyang
Notes

The road is still going on, the dream is still waiting

1、SpringBoot Actuator

1 Introduction

After every microservice is deployed on the cloud in the future, we need to monitor, track, audit, control, etc. SpringBoot extracts the Actuator scenario, so that each of our microservices can be quickly referenced to obtain production-level application monitoring, auditing and other functions.

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

insert image description here

2. The difference between 1.x and 2.x

insert image description here

3. How to use

● Introduce scenarios
● Visit http://localhost:8080/actuator/**
● Expose all monitoring information as 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
。。。。。。

4. Visualization

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

2、Actuator Endpoint

1. The most commonly used endpoints

ID describe
auditevents Exposes audit event information for the current application. Requires an AuditEventRepository component.
beans Displays a complete list of all Spring Beans in the application.
caches Expose available caches.
conditions Displays all condition information for auto-configuration, including the reason for the match or non-match.
configprops Show all @ConfigurationProperties.
env Exposes Spring properties ConfigurableEnvironment
flyway Shows all Flyway database migrations that have been applied.
Requires one or more Flyway components.
health Displays application health information.
httptrace Show HTTP trace information (by default, last 100 HTTP request-responses).
Requires an HttpTraceRepository component.
info Display application information.
integrationgraph Show the Spring integration graph.
Need to rely on spring-integration-core.
loggers Display and modify the configuration of logs in the application.
liquidbase Shows all Liquibase database migrations that have been applied.
Requires one or more Liquibase components.
metrics Displays "metrics" information for the current application.
mappings Displays a list of all @RequestMapping paths.
scheduledtasks Displays scheduled tasks in the application.
sessions Allows user sessions to be retrieved and deleted from a Spring Session-backed session store.
Requires a Servlet-based web application using Spring Session.
shutdown Causes the application to shut down gracefully.
Disabled by default.
startup ringApplication configures BufferingApplicationStartup.
threaddump Take a thread dump.

If your application is a web application (Spring MVC, Spring WebFlux or Jersey), the following additional endpoints are available:

ID describe
heapdump Return the hprof heap dump file.
jolokia Expose JMX beans via HTTP (requires the introduction of Jolokia, not applicable to WebFlux).
Need to introduce dependency jolokia-core.
logfile Return the contents of the log file (if the logging.file.name or logging.file.path properties have been set).
Support for using the HTTPRange header to retrieve the contents of a partial log file.
prometheus Exposes metrics in a format that the Prometheus server can scrape.
Need to rely on micrometer-registry-prometheus.

最常用的Endpoint
● Health:监控状况
● Metrics:运行时指标
● Loggers:日志记录

2、Health Endpoint

健康检查端点,我们一般用于在云平台,平台会定时的检查应用的健康状况,我们就需要Health Endpoint可以为平台返回当前应用的一系列组件健康状况的集合。
重要的几点:
● health endpoint返回的结果,应该是一系列健康检查后的一个汇总报告
● 很多的健康检查默认已经自动配置好了,比如:数据库、redis等
● 可以很容易的添加自定义的健康检查机制

insert image description here

3、Metrics Endpoint

提供详细的、层级的、空间指标信息,这些信息可以被pull(主动推送)或者push(被动获取)方式得到;
● 通过Metrics对接多种监控系统
● 简化核心Metrics开发
● 添加自定义Metrics或者扩展已有Metrics

insert image description here

4、管理Endpoints

1、开启与禁用Endpoints

● 默认所有的Endpoint除过shutdown都是开启的。
● 需要开启或者禁用某个Endpoint。配置模式为 management.endpoint..enabled = true

management:
  endpoint:
    beans:
      enabled: true

或者禁用所有的Endpoint然后手动开启指定的Endpoint

management:
  endpoints:
    enabled-by-default: false
  endpoint:
    beans:
      enabled: true
    health:
      enabled: true

2、暴露Endpoints

支持的暴露方式
● HTTP:默认只暴露health和info Endpoint
● JMX:默认暴露所有Endpoint
● 除过health和info,剩下的Endpoint都应该进行保护访问。如果引入SpringSecurity,则会默认配置安全访问规则

ID JMX Web
auditevents Yes No
beans Yes No
caches Yes No
conditions Yes No
configprops Yes No
env Yes No
flyway Yes Yes
health N/A No
httptrace Yes No
info Yes Yes
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
scheduledtasks Yes No
sessions Yes No
shutdown Yes No
startup Yes No
threaddump Yes No

3、定制 Endpoint

1、定制 Health 信息

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();
management:
    health:
      enabled: true
      show-details: always #总是显示详细信息。可显示每个模块的状态信息
@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 == 2){
    
    
//            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("code",100)
                .withDetails(map);

    }
}

2、定制info信息

常用两种方式

1、编写配置文件

info:
  appName: boot-admin
  version: 2.0.1
  mavenProjectName: @project.artifactId@  #使用@@可以获取maven的pom文件值
  mavenProjectVersion: @project.version@

2、编写InfoContributor

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 ExampleInfoContributor implements InfoContributor {
    
    

    @Override
    public void contribute(Info.Builder builder) {
    
    
        builder.withDetail("example",
                Collections.singletonMap("key", "value"));
    }

}

http://localhost:8080/actuator/info 会输出以上方式返回的所有info信息

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

class MyService{
    
    
    Counter counter;
    public MyService(MeterRegistry meterRegistry){
    
    
         counter = meterRegistry.counter("myservice.method.running.counter");
    }

    public void hello() {
    
    
        counter.increment();
    }
}


//也可以使用下面的方式
@Bean
MeterBinder queueSize(Queue queue) {
    
    
    return (registry) -> Gauge.builder("queueSize", queue::size).register(registry);
}

4、定制Endpoint

@Component
@Endpoint(id = "container")
public class DockerEndpoint {
    
    


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

    @WriteOperation
    private void restartDocker(){
    
    
        System.out.println("docker restarted....");
    }

}

Scenario: Develop ReadinessEndpoint to manage whether the program is ready, or LivenessEndpoint to manage whether the program is alive;
of course, this can also be used directly https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready -features.html#production-ready-kubernetes-probes

Guess you like

Origin blog.csdn.net/zhao854116434/article/details/130253292
21.