SpringBoot 从入门到光头 第十八章 SpringBoot 与监控管理


SpringBoot 从入门到光头 —— 第十八章 SpringBoot 与监控管理


1. 监控管理

通过引入 spring-boot-starter-actuator,可以使用 SpringBoot 为我们提供的准的生产环境下的应用监控和管理功能。我们可以通过 HTTP,JMX,SSH 协议来进行操作,自动得到审计、健康指标信息等

使用步骤:

  1. 引入 spring-boot-starter-actuator

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  2. 通过 HTTP 方式访问监控端点:http://127.0.0.1:8080/actuator/

  3. 在配置文件中暴露所有监控端点

    # management is the configuration of all actuators
    management:
      endpoints:
        enabled-by-default: true  # All monitoring endpoints are enabled by default
        web:
          exposure:
            include: '*'  # Expose all endpoints as web
    
  4. 可进行 Shutdown(POST 提交,此端点默认关闭)

SpringBoot 1.x 与 SpringBoot 2.x Actuator 的区别:

SpringBootActuatorVersion

一些常用的端点:

ID 描述
auditevents 暴露当前应用程序的审核事件信息。需要一个 AuditEventRepository 组件
beans 显示应用程序中所有 SpringBean 的完整列表
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 使应用程序正常关闭(POST提交,默认禁用)
startup 显示由 ApplicationStartup 收集的启动步骤数据。需要使用 SpringApplication 进行配置 BufferingApplicationStartup
threaddump 执行线程转储

2. 定制端点

  • 定制端点一般通过 endpoints + endpointName + propName 来设置
  • 修改端点 ID:endpoints.beans.id=myBeans
  • 定制端点访问路径:management.endpoints.web.bash-path=/manage
  • 定制端点访问端口:management.server.port=8181(可以通过设置端口为 -1 来关闭端点访问端口)

2.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 &#123;
    @Override
    public Health health() &#123;
        int errorCode = check(); // perform some specific health check
        if (errorCode != 0) &#123;
            return Health.down().withDetail("Error Code", errorCode).build();
        &#125;
        return Health.up().build();
    &#125;
&#125;

// 构建Health
Health build = Health.down()
                .withDetail("msg", "error service")
                .withDetail("code", "500")
                .withException(new RuntimeException())
                .build();

示例代码:

com.gregperlinli.adminserver.actuator.health.MyComHealthIndicator

/**
 * @author gregPerlinLi
 * @since 2021-11-22
 */
@Component
public class MyComHealthIndicator extends AbstractHealthIndicator &#123;
    /**
     * Real inspection method
     *
     * @param builder
     * @throws Exception
     */
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception &#123;
        Map<String, Object> map = new HashMap<>(1000);
        // Check completed
        if ( 1 == 1 ) &#123;
            // Health
            builder.status(Status.UP);
            map.put("count", 1);
            map.put("ms", 100);
        &#125; else &#123;
            // Unhealthy
            builder.status(Status.DOWN);
            map.put("error", "Connection time out!");
            map.put("ms", 3000);
        &#125;
        builder.withDetail("code", 100)
                .withDetails(map);
    &#125;
&#125;

application.yaml

management:
  # Specific configuration to an endpoint: endpoint.endpointName
  endpoint:
    health:
      show-details: always  # Details are always displayed, and the status information of each module can be displayed

2.2. 定制 Info 信息

常用两种方式编写

2.2.1. 编写配置文件

application.yaml

info:
  appName: boot-admin
  appVersion: 1.0.0
  mavenProjectName: @project.artifactId@  # Use @@ to get Maven's POM file value
  mavenProjectVersion: @project.version@

2.2.2. 编写 InfoContributor

com.gregperlinli.adminserver.acutuator.info.AppInfo

/**
 * @author gregPerlinLi
 * @since 2021-11-22
 */
@Component
public class AppInfo implements InfoContributor &#123;

    @Override
    public void contribute(Info.Builder builder) &#123;
        builder.withDetail("msg", "Hello!")
                .withDetail("hello", "world")
                .withDetails(Collections.singletonMap("123", "456"));
    &#125;
&#125;

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

2.3. 定制 Metrics 信息

2.3.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.3.2. 添加定制 Metrics

使用示例:

class MyService&#123;
    Counter counter;
    public MyService(MeterRegistry meterRegistry)&#123;
         counter = meterRegistry.counter("myservice.method.running.counter");
    &#125;
    public void hello() &#123;
        counter.increment();
    &#125;
&#125;

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

2.4. 定制 Endpoint

示例代码:

com.gregperlinli.adminserver.acutuator.endpoint.MyServiceEndpoint

/**
 * @author gregPerlinLi
 * @since 2021-11-22
 */
@Component
@Endpoint(id = "myService")
public class MyServiceEndpoint &#123;
    @ReadOperation
    public Map getDockerInfo() &#123;
        return Collections.singletonMap("dockerInfo", "docker started...");
    &#125;
    @WriteOperation
    public void stopDocker() &#123;
        System.out.println("Docker stopped...");
    &#125;
&#125;

场景:开发 ReadinessEndpoint 来管理程序是否就绪,或者 LivenessEndpoint 来管理程序是否存活;

当然,这个也可以直接参照以下链接

https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-kubernetes-probes



文章作者: gregPerlinLi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 gregPerlinLi !
  目录