適用於 Java 的 Micrometer 計量

適用於:NoSQL

適用於 Azure Cosmos DB 的 Java SDK 使用 Micrometer 來實作用戶端計量,以在 Prometheus 這類熱門可檢視性系統中進行檢測。 本文包括將取自此範例的計量抓取至 Prometheus 的指示和程式碼片段。 SDK 所提供的完整計量清單記載於這裡。 如果您的用戶端部署在 Azure Kubernetes Service (AKS) 上,則您也可以搭配使用適用於 Prometheus 的 Azure 監視器受管理服務與自訂抓取,請參閱這裡的文件。

從 Prometheus 取用計量

您可以從這裡下載 Prometheus。 若要使用 Prometheus 在適用於 Azure Cosmos DB 的 Java SDK 中取用 Micrometer 計量,請先確定您已匯入登錄和用戶端所需的程式庫:

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

<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_httpserver</artifactId>
    <version>0.5.0</version>
</dependency>

在您的應用程式中,將 Prometheus 登錄提供給遙測設定。請注意,您可以設定各種診斷閾值,這有助於限制取用您最感興趣的計量:

//prometheus meter registry
PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);

//provide the prometheus registry to the telemetry config
CosmosClientTelemetryConfig telemetryConfig = new CosmosClientTelemetryConfig()
        .diagnosticsThresholds(
                new CosmosDiagnosticsThresholds()
                        // Any requests that violate (are lower than) any of the below thresholds that are set
                        // will not appear in "request-level" metrics (those with "rntbd" or "gw" in their name).
                        // The "operation-level" metrics (those with "ops" in their name) will still be collected.
                        // Use this to reduce noise in the amount of metrics collected.
                        .setRequestChargeThreshold(10)
                        .setNonPointOperationLatencyThreshold(Duration.ofDays(10))
                        .setPointOperationLatencyThreshold(Duration.ofDays(10))
        )
        // Uncomment below to apply sampling to help further tune client-side resource consumption related to metrics.
        // The sampling rate can be modified after Azure Cosmos DB Client initialization – so the sampling rate can be
        // modified without any restarts being necessary.
        //.sampleDiagnostics(0.25)
        .clientCorrelationId("samplePrometheusMetrics001")
        .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(prometheusRegistry)
                //.configureDefaultTagNames(CosmosMetricTagName.PARTITION_KEY_RANGE_ID)
                .applyDiagnosticThresholdsForTransportLevelMeters(true)
        );

啟動本機 HttpServer 伺服器,以將計量登錄計量公開至 Prometheus:

try {
    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
    server.createContext("/metrics", httpExchange -> {
        String response = prometheusRegistry.scrape();
        int i = 1;
        httpExchange.sendResponseHeaders(200, response.getBytes().length);
        try (OutputStream os = httpExchange.getResponseBody()) {
            os.write(response.getBytes());
        }
    });
    new Thread(server::start).start();
} catch (IOException e) {
    throw new RuntimeException(e);
}

請確定您在建立 CosmosClient 時傳遞 clientTelemetryConfig

//  Create async client
client = new CosmosClientBuilder()
    .endpoint(AccountSettings.HOST)
    .key(AccountSettings.MASTER_KEY)
    .clientTelemetryConfig(telemetryConfig)
    .consistencyLevel(ConsistencyLevel.SESSION) //make sure we can read our own writes
    .contentResponseOnWriteEnabled(true)
    .buildAsyncClient();

將應用程式用戶端的端點新增至 prometheus.yml 時,將網域名稱和連接埠新增至「目標」。 例如,如果 prometheus 正在與應用程式用戶端相同的伺服器上執行,則您可以將 localhost:8080 新增至 targets,如下所示:

scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:9090", "localhost:8080"]

現在,您可以從 Prometheus 取用計量:

Screenshot of metrics graph in Prometheus explorer.

下一步