【Graphite】使用dropwizard.metrics向Graphite中写入指标项数据
graphite
定时向Graphite中写入指标项数据,指标项模拟个数3000个
使用的类库
官方文档
dropwizard的github地址
Metric官方文档
metrics.dropwizard的GitHub地址
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>${dropwizard.metrics.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-graphite</artifactId>
<version>${dropwizard.metrics.version}</version>
</dependency>
核心代码详解
配置Graphite地址
指定Graphite的host和port,默认时,Graphite中的carbon使用2003端口接收数据;
Graphite graphite = new Graphite(new InetSocketAddress("10.144.202.150", 2003));
模拟3000个指标项
每个指标项都有一个uuid,3000个uuid代表3000个不同的指标项
final List<String> uuids = Lists.newArrayList();
{
for (int i = 1000; i < 4000; i++) {
String uuid = "aaa" + i + "";
uuids.add(uuid);
}
}
定义Gauge指标
dropwizard.metrics支持5种指标类型,分别为:
- Gauge
- Counter
- Meter
- Histograms
- Timers
我们这里定义Gauge指标,需要实现Gauge接口;
使用metricValue(uuid)方法
模拟每个指标项的当前值
/**
* Gauge指标
*/
class GaugeImp implements Gauge<Float> {
String uuid;
public GaugeImp(String uuid) {
this.uuid = uuid;
}
@Override
public Float getValue() {
return metricValue(uuid);
}
}
/**
* 用于模拟指标值
*
* @param uuid
* @return
*/
private float metricValue(String uuid) {
Random random = new Random();
float value = random.nextFloat();
return value;
}
向Graphite中写入指标项
- 注册一个MetricRegistry:所有的指标项metrics都存在在MetricRegistry中;
- 注册所有需要写入的指标项:这里写入3000个Gauge指标;
- 使用GraphiteReporter实现向Graphite写入数据:A reporter which publishes metric values to a Graphite server.
- 开始定时任务,每隔5s中向Graphite中写入一次数据;
MetricRegistry registry = new MetricRegistry();
// 注册 gauge 指标
for (String uuid : uuids) {
String name = "resource." + uuid + ".size";
registry.register(name, new GaugeImp(uuid));
}
//A reporter which publishes metric values to a Graphite server.
GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
.prefixedWith("openmetric")
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.build(graphite);
// 设置每隔5秒钟,向Graphite中发送一次指标值
reporter.start(5, TimeUnit.SECONDS);
写入结果截图
相关文章