【问题标题】:How to make own metrics in Spring Boot for prometheus如何在 Spring Boot 中为 prometheus 制作自己的指标
【发布时间】:2021-08-10 14:32:27
【问题描述】:
@GetMapping(value = "/ownMetrics")
public String ownMetrics() {
     return "ownmetrics_age{Name=\"Age\",} " + age;
}

我想制作我自己的指标,并且采用 prometheus 可以读取的正确格式。

【问题讨论】:

    标签: java html rest prometheus metrics


    【解决方案1】:

    您可以将Micrometer 用于自定义指标并将其公开给prometheus。如果您使用的是 gradle,请添加以下依赖项:

    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-webflux'
    
        // metrics: micrometer + prometheus
        implementation 'org.springframework.boot:spring-boot-starter-actuator'
        implementation 'io.micrometer:micrometer-registry-prometheus:1.6.6'
    }
    

    在您的服务类中添加MeterRegistry 和Counter。启动Counter 并调用此计数器的incrementer。在我的示例中是bidderCallsCounter.increment();。我将指标名称定义为bidder.calls,Prometheus 将用_ 替换.。

    @Slf4j
    @Service
    public class YourService {
        private MeterRegistry meterRegistry;
        private Counter bidderCallsCounter;
        public YourService(MeterRegistry meterRegistry) {
            this.meterRegistry = meterRegistry;
        }
        private void initBidderCallCounter() {
            // CREATE A COUNTER
            bidderCallsCounter = this.meterRegistry.counter("bidder.calls", "type", "bidder");
        }
        private Stream<Flux<BidResponse>> bidResponseStreamMono(Mono<BidRequest> bidRequestMono) {
            return biddersWebClient.stream()
                    .map(bidderWebClient -> {
                        // THE INCREMENTER
                        bidderCallsCounter.increment();
                        return bidderWebClient.post()
                                ....
                                .log("BidResponse: ");
                    });
        }
    }
    

    然后,在您配置 Prometheus 目标后,访问 http://172.17.0.1:8080/actuator/prometheus,您可以看到可用的自定义指标。在屏幕截图中,您可以看到 Prometheus 抓取了指标 bidder_calls。

    scrape_configs:
      - job_name: 'spring-actuator'
        metrics_path: '/actuator/prometheus'
        scrape_interval: 5s
        static_configs:
          # this should be the target host IP which is outside of the docker:
          # 172.17.0.1   or   "export DOCKER_GATEWAY_HOST=$(hostname -I | awk '{print $1}')"
          - targets: [ '172.17.0.1:8080' ]
    

    【讨论】:

    • 是否可以通过带有@GetMapping 的方法传输指标?因为,我想使用 Swagger UI 来记录它。
    • AFAIK 这不是因为依赖spring-boot-starter-actuator 将指标暴露给外部http://localhost:8080/actuator/metrics。除非你重写你自己的执行器项目.....
    • 我正在考虑它,也许如果您将端点公开为actuator,您是否不需要导入 ita 依赖项而只使用micrometer。但我从来没有测试过...
    • 我会尝试不同的方法,也许我会找到一种可行的方法。如果我找到一个,那么我会发布它
    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 2019-08-09
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2021-05-07
    • 2022-01-17
    相关资源
    最近更新 更多