Java용 마이크로미터 메트릭

적용 대상: NoSQL

Azure Cosmos DB용 Java SDKPrometheus와 같이 널리 사용되는 관찰 시스템에서 계측을 위해 마이크로미터를 사용하여 클라이언트 메트릭을 구현합니다. 이 문서에는 이 샘플에서 가져온 메트릭을 Prometheus로 스크랩하는 방법에 대한 지침과 코드 조각이 포함되어 있습니다. SDK에서 제공하는 메트릭의 전체 목록은 여기에 설명되어 있습니다. 클라이언트가 AKS(Azure Kubernetes Service)에 배포된 경우 사용자 지정 스크래핑을 통해 Prometheus용 Azure Monitor 관리 서비스를 사용할 수도 있습니다. 여기에 있는 설명서를 참조하세요.

Prometheus의 메트릭 사용

여기에서 Prometheus를 다운로드할 수 있습니다. Prometheus를 사용하여 Azure Cosmos DB용 Java SDK에서 마이크로미터 메트릭을 사용하려면 먼저 레지스트리 및 클라이언트에 필요한 라이브러리를 가져왔는지 확인합니다.

<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가 앱 클라이언트와 동일한 서버에서 실행 중인 경우 아래와 같이 targetslocalhost:8080을 추가할 수 있습니다.

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.

다음 단계