Metrik mikrometer untuk Java

BERLAKU UNTUK: NoSQL

Java SDK untuk Azure Cosmos DB menerapkan metrik klien menggunakan Micrometer untuk instrumentasi dalam sistem pengamatan populer seperti Prometheus. Artikel ini mencakup petunjuk dan cuplikan kode untuk mengikis metrik ke Prometheus, yang diambil dari sampel ini. Daftar lengkap metrik yang disediakan oleh SDK didokumentasikan di sini. Jika klien Anda disebarkan di Azure Kubernetes Service (AKS), Anda juga dapat menggunakan layanan terkelola Azure Monitor untuk Prometheus dengan pengikisan kustom, lihat dokumentasi di sini.

Mengonsumsi metrik dari Prometheus

Anda dapat mengunduh prometheus dari sini. Untuk menggunakan metrik Micrometer di Java SDK untuk Azure Cosmos DB menggunakan Prometheus, pertama-tama pastikan Anda telah mengimpor pustaka yang diperlukan untuk registri dan klien:

<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>

Dalam aplikasi Anda, berikan registri prometheus ke konfigurasi telemetri. Perhatikan bahwa Anda dapat mengatur berbagai ambang diagnostik, yang akan membantu membatasi metrik yang dikonsumsi ke metrik yang paling Anda minati:

//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)
        );

Mulai server HttpServer lokal untuk mengekspos metrik registri meter ke 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);
}

Pastikan Anda lulus clientTelemetryConfig saat membuat CosmosClient:

//  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();

Saat menambahkan titik akhir untuk klien aplikasi Anda ke prometheus.yml, tambahkan nama domain dan port ke "target". Misalnya, jika prometheus berjalan di server yang sama dengan klien aplikasi, Anda dapat menambahkannya localhost:8080targets seperti di bawah ini:

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"]

Sekarang Anda dapat menggunakan metrik dari Prometheus:

Screenshot of metrics graph in Prometheus explorer.

Langkah berikutnya