学习 Metrics(一):初识 Metrics

Metrics 是 Java 用于监控系统度量指标的第三方库,被广泛应用于知名开源项目中,例如:Apache Hadoop、Apache Spark 中。

依赖

编辑 pom.xml 文件:

<dependencies>  
    <dependency>
        <groupId>io.dropwizard.metrics</groupId>
        <artifactId>metrics-core</artifactId>
        <version>${metrics.version}</version>
    </dependency>
</dependencies>  

当前 Metrics 最新版本为 4.0.0。

Registry

MetricRegistry 类即是 Metrics 的起始点,也是应用所有 metric 的集合。

MetricRegistry registry = new MetricRegistry();  

在 Registry 内每一个 metric 都有一个独一无二的名字,使用句点命名,例如 com.dyingbleed.demo.Application.requests

String metricName = MetricRegistry.name(Application.class, "requests");  
Meter meter = metrics.meter(metricName);  

监控类型

Gauge

Gauge(测量)是最简单的 metric 类型。它仅返回一个值。

registry.register("gauge", (Gauge<Integer>) () -> new Random().nextInt());  

运行结果:

gauge  
             value = 370907219

Counter

Counter(计数器)简单的增减 64 位的整型。

Counter counter = registry.counter("counter");  
counter.inc();  
counter.inc(3);  
counter.dec();  
counter.dec(5);  

运行结果:

counter  
             count = -2

Histogram

Histogram(分布直方图)度量流数据中值的分布情况。包括最大值、最小值、平均值、标准差,还包括分位数中位数、99 百分比等。

Histogram histogram = registry.histogram("histogram");  
histogram.update(1);  
histogram.update(3);  
histogram.update(5);  
histogram.update(7);  

运行结果:

histogram  
             count = 4
               min = 1
               max = 7
              mean = 4.00
            stddev = 2.24
            median = 5.00
              75% <= 7.00
              95% <= 7.00
              98% <= 7.00
              99% <= 7.00
            99.9% <= 7.00

Meter

Meter(计量表)度量事件集发生的速率。

Meter meter = registry.meter("meter");  
meter.mark();  

运行结果:

meter  
             count = 1
         mean rate = 0.99 events/second
     1-minute rate = 0.00 events/second
     5-minute rate = 0.00 events/second
    15-minute rate = 0.00 events/second

Timer

Timer(计时器)即度量了时间段内事件的分布,也度量了事件发生的速率。

Timer timer = registry.timer("timer");  
Timer.Context context = timer.time();

try {  
    Thread.sleep(new Random().nextInt(1000));
} finally {
    context.stop();
}

运行结果:

timer  
             count = 1
         mean rate = 0.99 calls/second
     1-minute rate = 0.00 calls/second
     5-minute rate = 0.00 calls/second
    15-minute rate = 0.00 calls/second
               min = 207.54 milliseconds
               max = 207.54 milliseconds
              mean = 207.54 milliseconds
            stddev = 0.00 milliseconds
            median = 207.54 milliseconds
              75% <= 207.54 milliseconds
              95% <= 207.54 milliseconds
              98% <= 207.54 milliseconds
              99% <= 207.54 milliseconds
            99.9% <= 207.54 milliseconds

Report

Report(报告)是应用导出指标的方式,Metrics 支持四类:JMX、命令行、SLF4J 和 CSV。

命令行:

ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics)  
    .convertRatesTo(TimeUnit.SECONDS)
    .convertDurationsTo(TimeUnit.MILLISECONDS)
    .build();
reporter.start(1, TimeUnit.SECONDS);