当前位置: 首页 > 工具软件 > Micrometer > 使用案例 >

Java 非Springboot/单jar包 下实现Micrometer+Prometheus载入

公冶嘉茂
2023-12-01

        

目录

0.引言

1.Springboot+Prometheus

连接配置:

pom文件添加:

定义统计字段:

操作统计字段:

2.非Springboot下,Micrometer+Prometheus

连接配置:

pom文件添加:

定义统计字段:

操作统计字段:


0.引言

        突然想起来以前做过一个给jar包加上Prometheus+granfana监控的功能,那个jar包没有用任何框架,而我在网上找了很久都是基于Springboot的载入,后来好像是在GitHub找到关键词,然后搜到了不需要框架的载入方法,翻到了笔记就保存一下,虽然以后可能用不上了。

        常规的基于Springboot的实现可自行搜其他更好的博客。。。

1.Springboot+Prometheus

连接配置:

application. properties:
server.port=8681
management.security.enabled=false //暴露springboot所有端口


启动类上面添加注解:
@EnablePrometheusEndpoint
@EnableSpringBootMetricsCollector

启动类里面添加一行:
DefaultExports.initialize();

pom文件添加:

<!-- The client -->
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient</artifactId>
        <version-0.9.0</version>
    </dependency>
    <!--Hotspot JM metrics-->
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient_hotspot</artifactId>
        <version>0.9.0</version>
    </dependency>
    <!-- Exposition HTTPServer-->
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient_httpserver</artifactId>
        <version>0.9.0</version>
    </dependency>
    <!-- Pushgateway exposition-->
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient_pushgateway</artifactId>
        <version>0.9.0</version>
    </dependency>
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient_spring_boot</artifactId>
        <version>0.9.0</version>
    </dependency>
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient_servlet</artifactId>
        <version>0.9.0</version>
    </dependency>

定义统计字段:

/** ASR 使用中的并发数及总并发数(单机) */
static final Gauge asr_using_license = Gauge.build().name("asr_using_license").help("asr using ldcense").register();
static final Gauge asr_total_license = Gauge.build().name("asr_total_license").help("asr total license").register();

/** ASR总请求数、错误请求数 */
static final Counter asr_requests_total = Counter.build().name("asr_requests_total").labe lNames("code").help("asr total requests").register();
static final Counter asr_requests_error_total = Counter.build().name("asr_requests_error total").help("asr total error requests").register();

/** ASR延迟直方图 */
// static final Histogram asr_latency_histogram = Histogram.build().labelNames("histogram").name("asr_latency_histogram").buckets(50,100,150,200,250,300).help("asr latency histogram").register();
static final Histogram asr_latency_histogram = Histogram.build().labelNames("histogram").name("asr_latency_histogram").bucets(0.5,1.0,1.5,2.0,2.5,3.0).help("asr latency histogram").register();

/**Summary暂时不用*/
static final Summary requestLatency = Summary.build()
    .quantile(0.5,0.05) // Add 50th percentile (= median) with 5% tolerated error
    .quantile(0.9,0.01) // Add 90th percentile with 1% tolerated error
        .labelNames ("labels")
    .name("requests_latency_seconds").help("Request latency in seconds.").register();

操作统计字段:

Gauge:
    public void asrUsingLicense(boolean add) {
        if(add) {
            asr_using_license.inc();
        } else {
            asr_using_license.dec();
        }
    }

Counter:
    public void asrRequestAdd(String code) {
        asr_requests_total.labels(code).inc();
        //asr_requests_total.inc();
    }

Histogram:
开始:
    public Histogram.Timer histogramStart(String lable) {
        Histogram.Timer timer=asr_latency_histogram.labels(lable).startTimer();
        return timer;
    }
结束:
    public void histogramStop(Histogram.Timer timer) {
        timer.observeDuration();
    }

注意: build时如果加了.labelNames(),对字段操作时也必须加.labels()。

2.非Springboot下,Micrometer+Prometheus

这里是手动启动了一个服务,没有修改配置的话地址固定"/prometheus"

连接配置:

PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
try {
    logger.info("---------8005 start");
    HttpServer server = HttpServer.create(new InetSocketAddress(8005), 1000);
    server.createContext("/prometheus", httpExchange -> {
        String response = prometheusRegistry.scrape();
        httpExchange.sendResponseHeaders(200, response.getBytes().length);
        try (OutputStream os = httpExchange.getResponseBody()){
            os.write(response. getBytes());
        }
    });
    logger.info("---------8005 info");
    new Thread(server::start).start();
    logger.info("---------8005 end");
} catch (IOException e){
    logger.error("prometheusRegistry init error!,e:{}",e.getMessage());
}

pom文件添加:

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
    <version>1.1.4</version>
</dependency>

定义统计字段:

有两种创建方式,1:

static final PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.OEFAULT);
static final Counter asr_requests_total = prometheusRegistry.counter("asr_requests_total");
static AtomicInteger asr_using_license = prometheusRegistry.gauge("asr_using_license",new AtomicInteger());
static final Timer timer = prometheusRegistry.timer("timer");

2:

static final AtomicInteger atomicInteger = new AtomicInteger();
static final Counter asr_requests_total1 = Counter.builder("asr_requests_total1")
    .tag("counter", "counter")
    .description("asr_requests_total1")
    .register(new SimpleMeterRegistry());
static final Gauge asr_using_license1 = Gauge.builder("asr_using_license1", atomicInteger, AtomicInteger::get)
    .tag("gauge", "gauge")
    .description("asr_using_license")
    .register(new SimpleMeterRegistry());
static final Timer timer1 = Timer.builder("timer1")
    .tag("timer1", "timer1")
    .description("timer1")
    .register(new SimpleMeterRegistry());

操作统计字段:

public void totalCounter() {
    asr_requests_total.increment();
}

public void asrUsingLicense(boolean add) {
    if(add) {
        asr_using_license.incrementAndGet();
    }else {
        asr_using_license.decrementAndGet();
    }
}
或第2种创建方式的:
public void asrUsingLicense1(boolean add) {
    if(add) {
        atomicInteger.incrementAndGet();
    }else {
        atomicInteger.decrementAndGet();
    }
}

timer的2种操作方式,1:
Timer.Sample sample = Timer.start(prometheusRegistry);
...(业务代码)
sample.stop(timer);

2:
timer.record(()->{
    ...(业务代码)
});

 类似资料: