Skip to content

Instantly share code, notes, and snippets.

@kkfnui
Created March 11, 2017 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkfnui/4905d879005d76acfd36b4cc6758bcbd to your computer and use it in GitHub Desktop.
Save kkfnui/4905d879005d76acfd36b4cc6758bcbd to your computer and use it in GitHub Desktop.
package com.huihui.stat;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Histogram;
import io.prometheus.client.exporter.PushGateway;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class PrometheusMetric {
private final CollectorRegistry registry = CollectorRegistry.defaultRegistry;
private final ConcurrentMap<String, Counter> counters = new ConcurrentHashMap<String, Counter>();
private final ConcurrentMap<String, Histogram> histograms = new ConcurrentHashMap<String, Histogram>();
private static volatile PrometheusMetric instance;
public static PrometheusMetric getInstance() {
if (instance == null) {
synchronized (PrometheusMetric.class) {
if (instance == null) {
instance = new PrometheusMetric();
}
}
}
return instance;
}
private PrometheusMetric() {
}
public void increment(String name) {
Counter counter = getOrRegisterCounter(name);
counter.inc();
}
public void increment(String name, double amt) {
Counter counter = getOrRegisterCounter(name);
counter.inc(amt);
}
public Histogram.Timer startTimer(String name) {
Histogram summary = getOrRegisterHistogram(name);
return summary.startTimer();
}
private Counter getOrRegisterCounter(String name) {
if (counters.containsKey(name)) {
return counters.get(name);
}
Counter counter = Counter.build().name(name).help(name).create();
Counter prev = counters.putIfAbsent(name, counter);
if (prev == null) {
registry.register(counter);
return counter;
} else {
return prev;
}
}
private Histogram getOrRegisterHistogram(String name) {
if (histograms.containsKey(name)) {
return histograms.get(name);
}
Histogram histogram = Histogram.build().name(name).help(name).create();
Histogram prev = histograms.putIfAbsent(name, histogram);
if (prev == null) {
registry.register(histogram);
return histogram;
} else {
return prev;
}
}
public void push(String host, String jobName) throws IOException {
PushGateway pg = new PushGateway(host);
pg.push(registry, jobName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment