Metryki mikrometrów dla języka Java

DOTYCZY: NoSQL

Zestaw Java SDK dla usługi Azure Cosmos DB implementuje metryki klienta przy użyciu mikrometru do instrumentacji w popularnych systemach obserwowania, takich jak Prometheus. Ten artykuł zawiera instrukcje i fragmenty kodu służące do złomowania metryk do rozwiązania Prometheus, pobrane z tego przykładu. Pełna lista metryk udostępnianych przez zestaw SDK jest udokumentowana tutaj. Jeśli klienci są wdrażani w usłudze Azure Kubernetes Service (AKS), możesz również użyć usługi zarządzanej Azure Monitor dla rozwiązania Prometheus z niestandardowym złomowaniem, zobacz dokumentację tutaj.

Korzystanie z metryk z rozwiązania Prometheus

Możesz pobrać prometheus z tego miejsca. Aby korzystać z metryk mikrometrów w zestawie JAVA SDK dla usługi Azure Cosmos DB przy użyciu rozwiązania Prometheus, najpierw upewnij się, że zaimportowaliśmy wymagane biblioteki dla rejestru i klienta:

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

W aplikacji podaj rejestr prometheus w konfiguracji telemetrii. Zwróć uwagę, że można ustawić różne progi diagnostyczne, co pomoże ograniczyć użycie metryk do najbardziej zainteresowanych:

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

Uruchom lokalny serwer HttpServer, aby uwidocznić metryki rejestru mierników w usłudze 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);
}

Upewnij się, że podczas clientTelemetryConfig tworzenia elementu 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();

Podczas dodawania punktu końcowego dla klienta aplikacji do prometheus.ymlprogramu dodaj nazwę domeny i port do lokalizacji "targets". Jeśli na przykład prometheus jest uruchomiony na tym samym serwerze co klient aplikacji, możesz dodać localhost:8080 do targets następującego polecenia:

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

Teraz możesz korzystać z metryk z rozwiązania Prometheus:

Screenshot of metrics graph in Prometheus explorer.

Następne kroki