dropwizard-metrics
Metrics is a Java library which gives you unparalleled insight into what your code does in production.
Metrics provides a powerful toolkit of ways to measure the behavior of critical components in your production environment.
Getting Started
Setting Up Maven
<dependencies>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>${metrics.version}</version>
</dependency>
</dependencies>
核心组件:MetricRegistry 及核心方法
这样实例化:
final MetricRegistry metrics = new MetricRegistry();
方法签名:
public T register(String name, T metric) throws IllegalArgumentException {…}
注册一个统计量Gauge
举例,要监测一个队列的长度,每次获取该统计量时返回队列长度:
package org.lanqiao.metrics.test;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import org.web2017.test.data.RandomData;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
public class MetricRegistryTest {
// 统计量注册表
final static MetricRegistry metricRegistry = new MetricRegistry();
final static Queue queue = new LinkedList();
public static void main(String[] args) {
//模拟填充队列
new Thread( () -> {
while (true) {
queue.add( RandomData.randomId() );
try {
TimeUnit.SECONDS.sleep( 3 );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} ).start();
//注册一个Gauge
metricRegistry.register( MetricRegistry.name( MetricRegistryTest.class, "queue","size" ), new Gauge<Integer>() {
@Override
public Integer getValue() {
return queue.size();
}
} );
//向控制台输出报告
//定义一个ConsoleReporter
ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.