Spring Boot Actuator 定制 Endpoint

350 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第26天,点击查看活动详情

一、定制 Endpoint

1-1、定制 Health指标信息

@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 {

    //真实的检查方法
    @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",100);
        }else {
//            builder.down();//不健康
            builder.status(Status.DOWN);
            map.put("error","连接超时");
            map.put("ms",3000);
        }

        builder.withDetail("code",100).withDetails(map);
    }
} 

1-2、定制info指标信息

常用两种方式

1、编写配置文件

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

2、编写InfoContributor

@Component
public class AppInfo implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("msg","hello")
                .withDetail("hello","world")
                .withDetails(Collections.singletonMap("world","6661121"));
    }
} 

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

1-3、定制Metrics指标信息

Spring Boot Actuator 为 Micrometer 提供了依赖管理和自动配置功能,Micrometer 是一个应用指标 facade(面门),支持多种监控系统,包括:

AppOptics,Azure Monitor,Netflix Atlas,CloudWatch,Datadog,Dynatrace,Elastic,Ganglia,Graphite,Humio,Influx/Telegraf,JMX,KairosDB,New Relic,Prometheus,SignalFx,Google Stackdriver,StatsD,和 Wavefront。

Micrometer作用:

  • 提供一些列api供我们操作指标
  • 提供了缓存、类加载器、GC、jvm内存\cpu 利用率 线程...指标 能够开箱即用
  • 已经融入springboot Actuator

docs.spring.io/spring-boot… JVM度量,报告利用率(JVM metrics, report utilization of):

    • 各种内存和缓冲池(Various memory and buffer pools)
    • 与垃圾收集有关的统计数据(Statistics related to garbage collection)
    • 线程利用率(Threads utilization)
    • 加载/卸载的类数(Number of classes loaded/unloaded)
  • CPU 指标-CPU metrics
  • 文件描述符度量-File descriptor metrics
  • Kafka 的消费者、生产者和流量指标-Kafka consumer, producer, and streams metrics
  • Log4j2度量: 记录每个level记录在 Log4j2中的事件数量-Log4j2 metrics: record the number of events logged to Log4j2 at each level
  • Logback度量: 记录每个级别登录到 Logback 的事件数量 —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 指标—Tomcat metrics (server.tomcat.mbeanregistry.enabled must be set to true for all Tomcat metrics to be registered)
  • Spring整合指标 Spring Integration metrics

Spring Integration 度量

1-3-1、增加定制Metrics

定制计量方法:

  • Counter

Counter是一种比较简单的Meter,它是一种单值的度量类型,或者说是一个单值计数器。

使用场景:

Counter的作用是记录XXX的总量或者计数值,适用于一些增长类型的统计,例如下单、支付次数、Http请求总量记录等等,

//记录下单总数
Metrics.counter("order.count", "order.channel", order.getChannel()).increment();
  • Timer Timer(计时器)适用于记录耗时比较短的事件的执行时间,通过时间分布展示事件的序列和发生频率。

使用场景:

根据个人经验和实践,总结如下:

  • 1、记录指定方法的执行时间用于展示。
  • 2、记录一些任务的执行时间,从而确定某些数据来源的速率,例如消息队列消息的消费速率等。
@Around(value = "execution(* com.tuling.service.*Service.*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    Timer timer = Metrics.timer("method.cost.time", "method.name", method.getName());
    ThrowableHolder holder = new ThrowableHolder();
    Object result = timer.recordCallable(() -> {
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            holder.throwable = e;
        }
        return null;
    });
    if (null != holder.throwable) {
        throw holder.throwable;
    }
    return result;
}
  • Gauge Gauge(仪表)是获取当前度量记录值的句柄,也就是它表示一个可以任意上下浮动的单数值度量Meter。

使用场景:

根据个人经验和实践,总结如下:

  • 1、有自然(物理)上界的浮动值的监测,例如物理内存、集合、映射、数值等。
  • 2、有逻辑上界的浮动值的监测,例如积压的消息、(线程池中)积压的任务等,其实本质也是集合或者映射的监测。
Metrics.gauge("message.gauge", Collection::size);
  • Summary

Summary(摘要)主要用于跟踪事件的分布,在Micrometer中,对应的类是DistributionSummary(分发摘要)。它的使用方式和Timer十分相似,但是它的记录值并不依赖于时间单位。

使用场景:

根据个人经验和实践,总结如下:

  • 1、不依赖于时间单位的记录值的测量,例如服务器有效负载值,缓存的命中率等。
DistributionSummary summary = Metrics.summary("test.summary");
summary.record(1);

1-3-2、其他定制方式:

方式1

class MyService{
    Counter counter;

    public CityServicimpl(MeterRegistry meterRegistry){
        // http://localhost:8080/actuator/metrics/cityService.saveCity.count
        counter = meterRegistry.counter("cityService.saveCity.count");
    }

    public void saveCity(City city) {
        counter.increment();
        cityMapper.insert(city);
    }
}

方式2:

@Bean
MeterBinder queueSize(Queue queue) {
    return (registry) -> Gauge.builder("queueSize", queue::size).register(registry);
}

1-4、定制Endpoint

@Component
@Endpoint(id = "myservice")
public class MyServiceEndPoint {

    @ReadOperation
    public Map getDockerInfo(){
        //端点的读操作  http://localhost:8080/actuator/myservice
        return Collections.singletonMap("dockerInfo","docker stated...");
    }

    @WriteOperation
    public void stopDoucker(){
        System.out.println("docker stopped...");

    }  

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