前言
原先用 dropwizard metrics 都是自己看json的没有接入一个图形化监控的服务,网上查到都是 dropwizard metrics+InfluxDB的方式接入grafana,由于新项目走的prometheus数据源,不想再增加维护复杂度了,发现prometheus有支持dropwizard,这里记录一下集成步骤
步骤
1.引入依赖
dropwizard metric 的依赖这里就不写了
<!-- dropwizard metric to prometheus -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_dropwizard</artifactId>
<version>yourversion</version>
</dependency>
2.代码
将你项目里的 MetricRegistry 通过 DropwizardExports 注册到 prometheus的默认收集器
// 导入
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.dropwizard.DropwizardExports;
// 逻辑
CollectorRegistry.defaultRegistry.register(new DropwizardExports(metrics));
我用的是prometheus server提供的http采集的方式,所以需要提供格式化输出的接口
tips:也可以通过pushgateway的方式推送到prometheus server
通过 prometheus 的 TextFormat 对数据进行格式化并写入Writer
// 导入
import io.prometheus.client.exporter.common.TextFormat;
// 逻辑
List<String> nameList = hp.getRequestParams("name");
Set<String> includedParam = nameList.isEmpty() ? Collections.emptySet() : new HashSet<>(nameList);
StringWriter stringWriter = new StringWriter();
TextFormat.write004(stringWriter, CollectorRegistry.defaultRegistry.filteredMetricFamilySamples(includedParam));
总结
prometheus提供了对dropwizard metrics的转换逻辑