雲原生監控系統Prometheus——Sprint Boot可視化監控


Sprint Boot可視化監控

 ++

集成Spring Boot的Prometheus三劍客:Micrometer + Prometheus + Grafana

一、用Micrometer儀表化JVM應用

  Micrometer(千分尺)是 Pivotal 為最流行的監控系統提供的一個簡單的儀表客戶端門面模式,允許儀表化 JVM 應用,而無須關心是哪個供應商提供的指標。

  官網:https://micrometer.io/

  As an instrumentation facade, Micrometer allows you to instrument your code with dimensional metrics with a vendor-neutral interface and decide on the monitoring system as a last step. Instrumenting your core library code with Micrometer allows the libraries to be included in applications that ship metrics to different backends.

  Contains built-in support for AppOptics, Azure Monitor, Netflix Atlas, CloudWatch, Datadog, Dynatrace, Elastic, Ganglia, Graphite, Humio, Influx/Telegraf, JMX, KairosDB, New Relic, Prometheus, SignalFx, Google Stackdriver, StatsD, and Wavefront.

  Spring Boot 2.x 在 spring-boot-actuator 中引入了 Micrometer。Spring Boot 2.x 對 Spring Boot 1.x 的指標進行了重構,從 https://micrometer.io 官網可以看到,Micrometer 也支持對接其他監控系統。Micrometer 和 Spring Boot、Prometheus 的橋接關系如下圖:

  通過門面模式接入 Micrometer 的監控系統,工整並且規范。用 Maven 依賴示例來說,其都是 micrometer-registry-XXX 類型的。

  比如,接入 JMX 的依賴示例如下(https://micrometer.io/docs/registry/jmx):

In Gradle:

  compile 'io.micrometer:micrometer-registry-jmx:latest.release'

Or in Maven:

  <dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-jmx</artifactId>
    <version>${micrometer.version}</version>
  </dependency>

  Micrometer 還包括開箱即用的緩存、類加載器、垃圾收集、處理器利用率、線程池以及更多針對可操作洞察的解決方案。

  Micrometer 中最重要的兩個概念是 Meters 和 Registry:

  • Meters

Micrometer packs with a supported set of Meter primitives including: Timer, Counter, Gauge, DistributionSummary, LongTaskTimer, FunctionCounter, FunctionTimer, and TimeGauge. Different meter types result in a different number of time series metrics. For example, while there is a single metric that represents a Gauge, a Timer measures both the count of timed events and the total time of all events timed.
A meter is uniquely identified by its name and dimensions. We use the term dimensions and tags interchangeably, and the Micrometer interface is Tag simply because it is shorter. As a general rule it should be possible to use the name as a pivot. Dimensions allow a particular named metric to be sliced to drill down and reason about the data. This means that if just the name is selected, the user can drill down using other dimensions and reason about the value being shown.

  • Registry

Meter is the interface for collecting a set of measurements (which we individually call metrics) about your application. Meters in Micrometer are created from and held in a MeterRegistry. Each supported monitoring system has an implementation of MeterRegistry. How a registry is created varies for each implementation.

Micrometer packs with a SimpleMeterRegistry that holds the latest value of each meter in memory and doesn’t export the data anywhere. If you don’t yet have a preferred monitoring system, you can get started playing with metrics by using the simple registry:

MeterRegistry registry = new SimpleMeterRegistry();

  在 Spring Boot 2.x 以后,Spring Boot Actuator 中用自帶的 Micrometer 來實現監控。下面我們來看看 Spring Boot 中如何集成 Prometheus。

二、在Spring Boot 2.x中集成Prometheus的方法

  Spring Boot 2.x 的 acutator 已經默認提供了 prometheus 調用的接口,但是需要依賴 micrometer-registry-prometheus(原文見Spring官網:https://docs.spring.io/spring-boot/docs/2.5.0/reference/htmlsingle/#legal 6.2.Endpoints),集成 Prometheus 可以分為如下4個步驟:

    • 引入 Maven 依賴。
    • application.properties 配置。
    • 通過 MeterBinder 接口實現 bind 方法並注冊到 MeterRegistry。(6.6.4. Registering Custom Metrics)
    • 指標埋點。

  2.1 引入 Maven 依賴

  因為 Spring Boot 2.x 在 Actuator 模塊中使用 Micrometer 來實現監控,所以要引入 spring-boot-starter-actuator 依賴(原文見Spring官網:https://docs.spring.io/spring-boot/docs/2.5.0/reference/htmlsingle/#legal 6.Spring Boot Actuator: Production-ready Features)。必要的 3 個配置分別是 spring-boot-starter-actuator、micrometer-registry-prometheus 和 micrometer-core。Maven 項目中 pom 文件的配置方式如下所示:

<!-- 監控系統健康情況的工具 https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuator -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>2.5.2</version>
</dependency>

<!-- 橋接 Prometheus https://mvnrepository.com/artifact/io.micrometer/micrometer-registry-prometheus -->
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
    <version>1.7.1</version>
</dependency>

<!-- micrometer 核心包,按需引入,使用 Meter 注解或手動埋點時需要 https://mvnrepository.com/artifact/io.micrometer/micrometer-core -->
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-core</artifactId>
    <version>1.7.1</version>
</dependency>

  推薦加入 micrometer-jvm-extras 依賴,它可以獲取 Spring Boot 的 JVM 信息,這些指標可以方便用戶基於 Grafana 繪制可視化的 JVM 監控大屏。

<!-- 獲取 jvm 相關信息,並展示在 Grafana上 https://mvnrepository.com/artifact/io.github.mweirauch/micrometer-jvm-extras -->
<dependency>
    <groupId>io.github.mweirauch</groupId>
    <artifactId>micrometer-jvm-extras</artifactId>
    <version>0.2.2</version>
</dependency>

  2.2 application.properties 配置暴露采集點信息

  對於 Spring Boot 2.x 而言,如果需要集成 Prometheus,那么 application.properties 的建議配置如下(參考Spring官網Appendix A: Common Application Properties:https://docs.spring.io/spring-boot/docs/2.5.0/reference/htmlsingle/#application-properties):

# spring.application.name屬性必須有,一般為自己項目名稱
spring.application.name=spring-boot-prometheus-demo
management.metrics.tags.application=${spring.application.name}

#Endpoint IDs that should be included or '*' for all.
management.endpoints.web.exposure.include=*
#Endpoint IDs that should be excluded or '*' for all.
management.endpoints.web.exposure.exclude=prometheus,metrics

#Whether to enable the shutdown endpoint.
management.endpoint.shutdown.enabled=true
#Whether, in the absence of any other exporter, exporting of metrics to an in-memory backend is enabled.
management.metrics.export.simple.enabled=fals

#Whether to enable the prometheus endpoint.
management.endpoint.prometheus.enabled=true
#Whether exporting of metrics to Prometheus is enabled.
management.metrics.export.prometheus.enabled=true

  可以通過如下命令遠程關閉 Spring Boot 微服務:

curl -X POST localhost:8080/actuator/shutdown

  2.3 自定義 metrics 類,實現 MeterBinder 接口采集和注冊指標

  通過 io.micrometer.core.instrument.binder.meterbinder 接口實現 bind 方法,並將要采集的指標注冊到 MeterRegistry。

  在這個案例中,我們通過注解的形式創建了一個 Spring Boot 中的 Component 組件 DemoMetrics,這個組件內置了一個計數器,用於對有計數需求的業務場景進行工具封裝。

  該組件內部代碼的示例如下所示:

package com.example.demo.metrics;
 
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import org.springframework.stereotype.Component;
 
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 

@Component
public class YarnMetrics implements MeterBinder {
    
    public Counter counter;
    public Map<String,Double> map
 
    //Map 對象,用於對該組件進行擴展
    //demoMetrics.map.put("x", counter1)
    //demoMetrics.map.put("y", counter2)
    //demoMetrics.map.put("z", counter3)
    //DemoMetrics 根據 Map 的 Key 的名稱 x/y/z 取出業務端埋點值
    DemoMeterics() {
        map = new HashMap<>();
 
    @Override
    public void bindTo(MeterRegistry registry) {
        //定義並注冊一個名稱為 prometheus.demo.counter 的計數器,標簽是 name:counter1
        this.counter = Counter.builder("prometheus.demo.counter").tags(new String[]{"name","counter1"}).description("demo counter").register(meterRegistry);
        //從業務端傳遞的 Map 中取出與 Key 對應的值放入注冊的 Gauge 儀表中,標簽是 name:gauge1
        Gauge.builder("prometheus.demo.gauge",map, x->x.get("x")).register(meterRegistry);
    }
}

  Counter 是一個只增不減的計數器,可以用來記錄請求或者錯誤的總量,比如 http_requests_total 等。

  Gauge 屬於可增可減的儀表盤,更多用來反映應用當前的狀態,比如主機當前空閑的內存 node_memory_MemFree 或者其他屬性。

  以上指標在上述代碼中都進行了定義以及設置了標簽。標簽組合可以更好地表示應用及應用中的監控項,特別是在集群中。

  2.4 以埋點的方式更新指標數據

  注冊完指標后就需要更新指標信息了。這里先略。

三、Spring Boot 2.x采集並可視化相關數據

  Spring Boot 2.x 通過 Micrometer 提供了監控數據,但是這些數據並沒有可視化,所以不夠友好。如果要可視化,還需要我們執行兩個操作:

    • Prometheus 配置輪詢采集 Spring Boot 2.x 的應用 target 提供的數據。
    • Grafana 將 Prometheus 作為數據源可視化大盤展示。

  第一項操作可以在 Prometheus 里的 prometheus.yml 文件中加上 Spring Boot 2.x 應用 8080 端口的 Job 采集,並重新加載配置文件即可,這樣就可以將 Spring Boot 2.x的數據采集到 Prometheus 中。

scrape_configs:
  - job_name: 'prometheus'        # Prometheus 自身配置
    static_configs:
    - targets: ['localhost: 9090']

  - job_name: 'springboot-demo'    # Spring Boot 2.x 應用數據采集
    metrics_path: '/actuator/prometheus'
    static_configs:
    - targets: ['localhost: 8080']

   如上配置所示,http://localhost:8080/actuator/prometheus 頁面中 Spring Boot 2.x 所應用的數據會被采集到 Prometheus 中。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM