Sdílet prostřednictvím


Metriky mikrometrů pro Javu

PLATÍ PRO: NoSQL

Sada Java SDK pro Azure Cosmos DB implementuje klientské metriky pomocí mikrometrů pro instrumentaci v oblíbených systémech pozorovatelnosti, jako je Prometheus. Tento článek obsahuje pokyny a fragmenty kódu pro výstřižky metrik do Prometheus převzaté z této ukázky. Úplný seznam metrik poskytovaných sadou SDK je zde zdokumentovaný. Pokud jsou vaši klienti nasazeni ve službě Azure Kubernetes Service (AKS), můžete také použít spravovanou službu Azure Monitor pro Prometheus s vlastním výstřižkem, viz dokumentace tady.

Využití metrik z Prometheus

Zde si můžete stáhnout prometheus. Pokud chcete využívat metriky mikrometrů v sadě Java SDK pro Azure Cosmos DB pomocí nástroje Prometheus, nejprve se ujistěte, že jste naimportovali požadované knihovny pro registr a 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>

V aplikaci zadejte registr prometheus ke konfiguraci telemetrie. Všimněte si, že můžete nastavit různé prahové hodnoty diagnostiky, které vám pomůžou omezit metriky spotřebované na ty, které vás zajímají nejvíce:

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

Spusťte místní server HttpServer a zpřístupňte metriky registru měřiče pro 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);
}

Ujistěte se, že při vytváření CosmosClientpředáteclientTelemetryConfig:

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

Když do prometheus.ymlklienta aplikace přidáte koncový bod, přidejte název domény a port do cíle. Pokud je například prometheus spuštěný na stejném serveru jako váš klient aplikace, můžete ho přidat localhost:8080 targets takto:

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

Teď můžete využívat metriky z Prometheus:

Snímek obrazovky s grafem metrik v Průzkumníku Prometheus

Další kroky