Mikrometermått för Java

GÄLLER FÖR: NoSQL

Java SDK för Azure Cosmos DB implementerar klientmått med hjälp av Mikrometer för instrumentation i populära observerbarhetssystem som Prometheus. Den här artikeln innehåller instruktioner och kodfragment för att skrapa mått i Prometheus, som hämtats från det här exemplet. Den fullständiga listan över mått som tillhandahålls av SDK:et dokumenteras här. Om dina klienter distribueras i Azure Kubernetes Service (AKS) kan du även använda den hanterade Azure Monitor-tjänsten för Prometheus med anpassad skrapning. Mer information finns i dokumentationen här.

Använda mått från Prometheus

Du kan ladda ned prometheus härifrån. Om du vill använda mikrometermått i Java SDK för Azure Cosmos DB med prometheus kontrollerar du först att du har importerat de bibliotek som krävs för register och klient:

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

I ditt program anger du prometheus-registret till telemetrikonfigurationen. Observera att du kan ange olika diagnostiktrösklar, vilket hjälper dig att begränsa de mått som används till de som du är mest intresserad av:

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

Starta den lokala HttpServer-servern för att exponera mätarregistermåtten för 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);
}

Se till att du skickar clientTelemetryConfig när du skapar :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();

När du lägger till slutpunkten för programklienten i prometheus.ymllägger du till domännamnet och porten i "mål". Om prometheus till exempel körs på samma server som appklienten kan du lägga till localhost:8080targets följande:

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

Nu kan du använda mått från Prometheus:

Screenshot of metrics graph in Prometheus explorer.

Nästa steg