[17.0.0.3 and later]

MicroProfile 메트릭 인스트루먼테이션 API

MicroProfile 메트릭 API를 사용하여 애플리케이션에 메트릭을 추가할 수 있습니다. MicroProfile 메트릭 API는 Dropwizard 메트릭 API와 유사합니다.

MicroProfile 메트릭의 아키텍처

mpMetrics-1.0mpMetrics-1.1 기능은 메트릭이 저장되는 세 개의 메트릭 레지스트리를 제공합니다.
기본
기본 레지스트리는 MicroProfile 메트릭 스펙의 필요에 따라 서버의 메트릭에 사용됩니다.
벤더
Liberty의 경우 벤더 레지스트리는 제품 벤더로 추가되는 메트릭에 사용됩니다.
애플리케이션
애플리케이션 레지스트리는 애플리케이션으로 추가되는 메트릭에 사용됩니다. 애플리케이션 레지스트리는 기본 MetricRegistry입니다.

mpMetrics-1.0mpMetrics-1.1 기능에는 상호작용할 브라우저 및 모니터링 도구에 HTTP 인터페이스를 제공하는 /metrics 엔드포인트도 포함됩니다.

메트릭의 값 확인

MicroProfile 메트릭은 HTTP를 사용하여 액세스할 수 있는 /metrics 엔드포인트를 제공합니다. Liberty 서버가 적절한 구성으로 시작된 후 브라우저에서 메트릭을 볼 수 있습니다.

다음 URL 형식 예제는 메트릭을 볼 수 있는 주소에 대해 설명합니다.
https://localhost:9443/metrics

일반적으로 운영 팀은 도구를 구성하여 시간 경과에 따라 메트릭 값을 모니터링하고 레코드합니다.

애플리케이션에 메트릭 추가

애플리케이션에 메트릭을 추가하려면 메트릭이 시스템에 알려지고 /metrics 엔드포인트에서 보고될 수 있도록 애플리케이션 레지스트리로 메트릭을 작성하고 등록해야 합니다. 다음 방법을 사용하여 메트릭을 작성하고 등록할 수 있습니다.
  • MetricRegistry 직접 사용. 이 메소드를 사용하여 애플리케이션 코드는 명시적으로 메트릭을 작성하고 등록합니다.
  • CDI를 사용하여 메트릭 삽입. 이 메소드를 사용하여 메트릭은 명시적으로 CDI로 작성되고 애플리케이션 MetricRegistry에 등록됩니다.
  • 메트릭 어노테이션 사용. 이 메소드를 사용하여 메트릭은 명시적으로 CDI로 작성되고 애플리케이션 MetricRegistry에 등록됩니다.

직접 MetricRegistry 관리

MetricRegistry는 모든 메트릭 및 각각의 메타데이터를 저장합니다. 제공되는 메소드를 사용하여 메트릭 및 메타데이터를 등록하고 검색할 수 있습니다. 기본적으로 모든 애플리케이션 관련 메트릭은 단일 애플리케이션 범위의 MetricRegistry에 추가됩니다.

CDI 인젝션을 사용하여 애플리케이션 메트릭 레지스트리를 얻을 수 있습니다.
@Inject
MetricRegistry registry;

메트릭 등록

MetricRegistry 클래스에는 카운터, 미터, 히스토그램 및 타이머를 검색하거나 작성할 수 있는 메소드가 있습니다.

레지스트리는 이름이 같은 메트릭이 존재하는지 확인합니다. 메트릭이 존재하면 리턴됩니다.
Metadata counterMetadata = new Metadata(…);
…
 
// Create or retrieve the metric by Metadata.getName()
Counter counterMetric = registry.counter(counterMetadata);
Timer timerMetric =  registry.timer(timerMetadata);
Histogram histogramMetric =  registry.histogram(histogramMetadata);
Meter meterMetric =  registry.meter(meterMetadata);
 
// Register a gauge metric by Metadata.getName()
registry.register("gaugeMetric", gaugeMetric, gaugeMetadata);

메타데이터를 사용하여 메트릭 설명

메타데이터는 메트릭에 대한 정보를 설명하고 요약하는 데이터 세트이며 다른 유형의 메트릭을 좀 더 쉽게 찾고 작업할 수 있도록 합니다. 메타데이터는 속성 레벨에서 정보를 정의할 수 있을 정도의 세부 단위일 수 있습니다.

메트릭 메타데이터는 다음 속성으로 구성됩니다.

메타데이터는 각 메트릭의 용도를 더 잘 설명할 수 있습니다. 이 정보는 REST API를 통해 메트릭에 액세스할 때 유용합니다.
단위
문자열 단위의 고정된 세트입니다.
유형
게이지, 카운터, 미터, 히스토그램 또는 타이머
설명
사용자가 읽을 수 있는 메트릭에 대한 설명입니다.
표시 이름
사람이 읽을 수 없는 메트릭 이름을 표시하기 위한 사용자가 쉽게 읽을 수 있는 메트릭의 이름입니다(예: 메트릭 이름이 UUID인 경우).
태그
쉼표로 구분된 키와 값(key=value) 쌍 목록입니다.
[18.0.0.1 and later]재사용가능
[18.0.0.1 and later]MicroProfile 메트릭 버전 1.1 이상에서 재사용가능은 메트릭 이름을 재사용할 수 있음을 나타내는 부울입니다. 예를 들어, 다중 메소드의 어노테이션을 작성하는 동안 단일 메트릭을 재사용하려는 경우입니다.
환경 변수 MP_METRICS_TAGS에 쉼표로 구분된 name=value 쌍 목록을 전달하여 글로벌 또는 애플리케이션 전체의 태그를 설정할 수 있습니다.
export MP_METRICS_TAGS=app=shop,node=2932

[18.0.0.1 and later]MicroProfile 구성을 사용하여 MP_METRICS_TAGS를 구성할 수도 있습니다. MP_METRICS_TAGS 구성 방법에 대한 자세한 정보는 Liberty 런타임의 올바른 구성 값 위치의 내용을 참조하십시오.

메타데이터는 프로세스의 수명 동안 변경할 수 없습니다. 예를 들어, 하나의 검색에서 초로, 다른 검색에서 시간으로 단위를 리턴할 수 없습니다.
참고: DisplayName이 제공되지 않으면 메트릭의 기본 이름은 오브젝트의 이름입니다.

카운터

카운터는 증분 또는 감분 개수를 유지하는 데 사용되는 메트릭입니다. 카운터의 초기 값은 0으로 설정되며 inc() 또는 inc(long n)를 사용하여 증분되고 dec() 또는 dec(long n)를 사용하여 감분될 수 있습니다.

카운터를 사용하여 수신된 요청의 총 수 또는 동시 활성 HTTP 세션의 총 수를 계수할 수 있습니다.

다음 예제는 카운터를 사용하여 /donations REST 엔드포인트에 대한 히트의 수를 측정합니다.
Metadata statsHitsCounterMetadata = new Metadata(
    "statsHits",                                // name
    "Stats Hits",                               // display name
    "Number of hits on the /stats endpoint",    // description
    MetricType.COUNTER,                         // type
    MetricUnits.NONE);                          // units
 
Counter statsHitsCounter = registry.counter(statsHitsCounterMetadata);
@GET
@Path("/donations")
public String getTotalDonations() {
    statsHitsCounter.inc();
    return "$" + donationManager.getTotalDonations();
}
다음 결과는 REST 엔드포인트에서 생성됩니다.
curl -k -u user:password https://localhost:9443/metrics/application/statsHits
# TYPE application:stats_hits counter
# HELP application:stats_hits Number of hits on the /stats endpoint
application:stats_hits 213

curl -k -u user:password -H “Accept: application/json” https://localhost:9443/metrics/application/statsHits
{"statsHits":213}

게이지

게이지는 값을 얻기 위해 샘플링되는 메트릭을 나타냅니다.

게이지는 개발자가 구현해야 하는 인터페이스입니다. 게이지의 구현이 정의되지 않으므로 .register() 메소드를 사용하여 MetricRegistry에 수동으로 등록되어야 합니다. register()가 메트릭당 한 번만 사용되는지 확인하십시오. 같은 이름으로 두 개의 메트릭을 등록할 수 없습니다. 게이지를 사용하여 CPU 온도를 측정하거나 디스크 사용량을 측정합니다.

다음 예제는 목표에 도달하는 방향으로 현재 진행상태를 백분율로 표시하는 데 사용되는 게이지에 대해 설명합니다.
Gauge<Double> progressGauge = new Gauge<Double>() {
    public Double getValue() {
        return (double) getTotalDonations()
             / (double) getGoal() * 100.0;
    }
};
 
// Gauge
Metadata progressMetadata = new Metadata(
    "progress",                                     // name
    "Donation Progress",                            // display name
    "The percentage of the goal achieved so far",   // description
    MetricType.GAUGE,                               // type
    MetricUnits.PERCENT);                           // units
 
registry.register(progressMetadata.getName(), progressGauge, progressMetadata);
다음 결과는 REST 엔드포인트에서 생성됩니다.
curl -k -u user:password https://localhost:9443/metrics/application/progress
# TYPE application:progress_percent gauge
# HELP application:progress_percent The percentage of the goal achieved so far
application:progress_percent 4.472

curl -k -u user:password -H "Accept: application/json" https://localhost:9443/metrics/application/progress
{"progress":4.472}

미터

미터는 처리량을 추적하는 데 사용됩니다.

미터를 사용하려면 meter.mark() 메소드를 호출하여 이벤트를 표시해야 합니다. 다중 이벤트의 경우 mark(long n)를 사용하여 이벤트가 동시에 여러 번 발생함을 표시할 수도 있습니다. 미터는 다음 정보를 제공합니다.
  • 평균 처리량
  • 1/5/15분 지수가중이동평균 처리량
  • 측정 수의 계수

미터를 사용하여 애플리케이션에서 처리하는 트랜잭션의 속도를 계산할 수 있습니다.

다음 예제는 미터를 사용하여 getProcess()가 호출되는 해당 속도를 결정합니다. 빠른 속도는 결과가 캐시되어야 하거나 속도 제한이 적용되어야 함을 표시할 수 있습니다.
Metadata getProgressMeterMetadata = new Metadata(
    "getProgressMeter",                             // name
    "getProgress Call Rate",                        // display name
    "The rate of getProgress calls",                // description
    MetricType.METERED,                             // type
    MetricUnits.SECONDS);                           // units
Meter getProgressMeter = registry.meter(getProgressMeterMetadata);
public Double getProgress() {
    getProgressMeter.mark();
    return (double) getTotalDonations()/(double) getGoal() * 100.0;
}
다음 결과는 REST 엔드포인트에서 생성됩니다.
curl -k -u user:password https://localhost:9443/metrics/application/getProgressMeter1
# TYPE application:get_progress_meter_total counter
# HELP application:get_progress_meter_total The rate of getProgress calls
application:get_progress_meter_total 78
# TYPE application:get_progress_meter_rate_per_second gauge
application:get_progress_meter_rate_per_second 0.6584919803150174
# TYPE application:get_progress_meter_one_min_rate_per_second gauge
application:get_progress_meter_one_min_rate_per_second 0.5851884005757912
# TYPE application:get_progress_meter_five_min_rate_per_second gauge
application:get_progress_meter_five_min_rate_per_second 1.4218610926179416
# TYPE application:get_progress_meter_fifteen_min_rate_per_second gauge
application:get_progress_meter_fifteen_min_rate_per_second 1.6627979138032118

curl -k -u user:password -H "Accept: application/json" https://localhost:9443/metrics/application/getProgressMeter
	{
   "getProgressMeter": {
       "count": 78,
       "fifteenMinRate": 1.6627979138032118,
       "fiveMinRate": 1.4218610926179416,
       "meanRate": 0.6584919803150174,
       "oneMinRate": 0.5851884005757912
   }
}

히스토그램

히스토그램은 값의 분포를 저장하는 데 사용됩니다.

히스토그램의 값을 레코드하려면 레코드할 값으로 histogram.update(long value)를 호출해야 합니다. getSnapshot()을 사용하여 히스토그램의 현재 상태(또는 스냅샷)를 검색할 수 있습니다. MicroProfile 메트릭의 히스토그램은 정수 또는 긴 값만 지원합니다.

히스토그램은 다음 정보를 제공합니다.
  • 최대/최소/평균값
  • 50번째, 75번째, 95번째, 98번째, 99번째 백분위수의 값
  • 값 수의 계수

히스토리 예제에는 검색되는 페이로드의 분포 또는 가계 소득의 분포를 수집하는 온보딩 설문조사의 분포가 포함됩니다.

다음 예제는 기부의 값을 저장하는 데 사용되는 히스토그램에 대해 설명합니다. 이 예제에서는 기부 금액의 분포에 대한 아이디어가 있는 관리자를 제공합니다.
Metadata donationDistributionMetadata = new Metadata(
    "donationDistribution",                      // name
    "Donation Distribution",                     // display name
    "The distribution of the donation amounts ", // description
    MetricType.HISTOGRAM,                        // type
    “dollars”);                                  // units
Histogram donationDistribution = registry.histogram(donationDistributionMetadata);
public void addDonation(Long amount) {
    totalDonations += amount;
    donations.add(amount);
    donationDistribution.update(amount);
}
다음 결과는 REST 엔드포인트에서 생성됩니다.
curl -k -u user:password https://localhost:9443/metrics/application/com.example.samples.donationapp.DonationManager.donationDistribution

# TYPE application:com_example_samples_donationapp_donation_manager_donation_distribution_mean_dollars gauge
application:com_example_samples_donationapp_donation_manager_donation_distribution_mean_dollars 19.300015535407777
# TYPE application:com_example_samples_donationapp_donation_manager_donation_distribution_max_dollars gauge
application:com_example_samples_donationapp_donation_manager_donation_distribution_max_dollars 102.0
# TYPE application:com_example_samples_donationapp_donation_manager_donation_distribution_min_dollars gauge
application:com_example_samples_donationapp_donation_manager_donation_distribution_min_dollars 3.0
# TYPE application:com_example_samples_donationapp_donation_manager_donation_distribution_stddev_dollars gauge
application:com_example_samples_donationapp_donation_manager_donation_distribution_stddev_dollars 26.35464238355834
# TYPE application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars summary
# HELP application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars The distribution of the donation amounts
application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars_count 203
application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars{quantile="0.5"} 5.0
application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars{quantile="0.75"} 24.0
application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars{quantile="0.95"} 83.0
application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars{quantile="0.98"} 93.0
application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars{quantile="0.99"} 101.0
application:com_example_samples_donationapp_donation_manager_donation_distribution_dollars{quantile="0.999"} 102.0

curl -k -u user:password -H "Accept: application/json" https://localhost:9443/metrics/application/com.example.samples.donationapp.DonationManager.donationDistribution
	{
    "com.example.samples.donationapp.DonationManager.donationDistribution": {
        "count": 203,
        "max": 102,
        "mean": 19.300015535407777,
        "min": 3,
        "p50": 5.0,
        "p75": 24.0,
        "p95": 83.0,
        "p98": 93.0,
        "p99": 101.0,
        "p999": 102.0,
        "stddev": 26.35464238355834
    }
}

타이머

타이머는 타이밍 지속 기간을 집계하고 지속 기간 및 처리량 통계를 제공하는 데 사용됩니다.

일부 코드의 타이밍을 맞추기 위해 timer.context 오브젝트를 리턴하는 timer.time()을 호출할 수 있습니다. 이 컨텍스트는 context.close()를 호출하여 타이머를 중지하는 데 사용됩니다. 타이머에서 검색되는 정보는 타이밍 지속 기간의 미터와 히스토그램의 조합입니다.

타이머는 다음 정보를 제공합니다.
  • 최대/최소/평균 시간
  • 50번째, 75번째, 95번째, 98번째, 99번째 백분위수의 시간 값
  • 평균 처리량
  • 1/5/15분 지수가중이동평균 처리량
  • 시간 제한 이벤트 수의 계수

타이머를 사용할 수 있는 예제에는 복잡한 로직에 대한 측정 응답 시간 및 측정 처리 시간이 포함됩니다.

다음 예제는 기부를 통해 선형 검색에 대한 런타임을 측정하는 데 사용되는 타이머에 대해 설명합니다.
Metadata topDonationCalcTimerMetadata = new Metadata(
    "topDonationCalcTimer",                             // name
    "Top Donation Calculation Time",                    // display name
    "Processing time to find the top donation",         // description
    MetricType.TIMER,                                   // type
    MetricUnits.NANOSECONDS);                           // units
Timer topDonationCalcTimer = registry.timer(topDonationCalcTimerMetadata);
public Long getTopDonation() {
 
    // Start timing here
    Timer.Context context = topDonationCalcTimer.time();
 
    Long max = 0L;
    for (Long amount : donationManager.getDonationsList()) {
        max = amount > max ? amount : max;
    }
 
    // Stop timing
    context.close();
    return max;
}
다음 결과는 REST 엔드포인트에서 생성됩니다.
curl -k -u user:password https://localhost:9443/metrics/application/topDonationCalcTimer

# TYPE application:top_donation_calc_timer_rate_per_second gauge
application:top_donation_calc_timer_rate_per_second 0.19107302754898328
# TYPE application:top_donation_calc_timer_one_min_rate_per_second gauge
application:top_donation_calc_timer_one_min_rate_per_second 0.013233974568205872
# TYPE application:top_donation_calc_timer_five_min_rate_per_second gauge
application:top_donation_calc_timer_five_min_rate_per_second 0.4845914744130395
# TYPE application:top_donation_calc_timer_fifteen_min_rate_per_second gauge
application:top_donation_calc_timer_fifteen_min_rate_per_second 0.8866728789348088
# TYPE application:top_donation_calc_timer_mean_seconds gauge
application:top_donation_calc_timer_mean_seconds 9.37780684853573E-5
# TYPE application:top_donation_calc_timer_max_seconds gauge
application:top_donation_calc_timer_max_seconds 1.97197E-4
# TYPE application:top_donation_calc_timer_min_seconds gauge
application:top_donation_calc_timer_min_seconds 4.9630000000000004E-5
# TYPE application:top_donation_calc_timer_stddev_seconds gauge
application:top_donation_calc_timer_stddev_seconds 3.082659934664267E-5
# TYPE application:top_donation_calc_timer_seconds summary
# HELP application:top_donation_calc_timer_seconds Processing time to find the top donation
application:top_donation_calc_timer_seconds_count 63
application:top_donation_calc_timer_seconds{quantile="0.5"} 8.6069E-5
application:top_donation_calc_timer_seconds{quantile="0.75"} 1.0372E-4
application:top_donation_calc_timer_seconds{quantile="0.95"} 1.53694E-4
application:top_donation_calc_timer_seconds{quantile="0.98"} 1.96615E-4
application:top_donation_calc_timer_seconds{quantile="0.99"} 1.97197E-4
application:top_donation_calc_timer_seconds{quantile="0.999"} 1.97197E-4

curl -k -u user:password -H "Accept: application/json" https://localhost:9443/metrics/application/topDonationCalcTimer
{
   "topDonationCalcTimer": {
       "count": 63,
       "fifteenMinRate": 0.8866728789348088,
       "fiveMinRate": 0.4845914744130395,
       "max": 197197,
       "mean": 93778.06848535729,
       "meanRate": 0.19107302754898328,
       "min": 49630,
       "oneMinRate": 0.013233974568205872,
       "p50": 86069.0,
       "p75": 103720.0,
       "p95": 153694.0,
       "p98": 196615.0,
       "p99": 197197.0,
       "p999": 197197.0,
       "stddev": 30826.599346642666
   }
}

CDI를 사용하여 메트릭 삽입

CDI 인젝션은 메트릭이 작성되고 MetricRegistry에 등록되는 가장 쉬운 방법을 제공합니다. 메타데이터 오브젝트 작성 대신 @Metric 어노테이션의 매개변수를 사용하여 메트릭 메타데이터를 지정할 수 있습니다.
  • @Metric: 삽입되는 메트릭에 대해 설명하는 어노테이션. 이 어노테이션은 미터, 타이머, 카운터 및 히스토그램 유형의 필드에 사용될 수 있습니다.
  • @Metric 매개변수: name, displayname, units, tags, description, absolute
    @Metric 어노테이션의 매개변수는 해당 메타데이터 필드와 유사하며 차이점은 다음과 같습니다.
    • tags: key=value 태그 문자열의 배열
    • absolute: true인 경우, 메트릭 이름을 이름 매개변수에 지정된 정확한 이름으로 설정하십시오. false인 경우, 접두부를 패키지 클래스 및 이름에 추가하여 완전한 이름을 사용하십시오.
    @Inject
    @Metric(name="statsHits", displayName="Stats Hits", description="Number of hits on the /stats endpoint", absolute=true)
    Counter statsHitsCounter;
    서버는 MetricRegistry에서 카운터를 작성하고 등록하며 애플리케이션에서 사용하는 카운터를 제공합니다. 카운터 예제는 statsHitsCounter 예제와 동일합니다. absolute=true는 제공된 이름이 그대로 사용됨을 의미합니다. 단위 매개변수는 사용되지 않고 MetricUnits.NONE이 기본값으로 설정됩니다.
    @Inject
    @Metric(name= "topDonationCalcTimer", unit = MetricUnits.NANOSECONDS, description="Processing time to find the top donation")
    Timer topDonationCalcTimer;
    
    @Inject
    @Metric(absolute = true, tags=["appName=DonationApp"])
    Counter counted;
두 예제는 다른 매개변수를 사용하여 메트릭을 삽입하는 방법에 대해 설명합니다.

메트릭 어노테이션

MicroProfile 메트릭에는 @Counted, @Timed, @Metered@Gauge 어노테이션을 처리하기 위한 다수의 인터셉트도 있습니다.

@Metric 어노테이션과 마찬가지로, 직접 어노테이션을 사용하여 각 어노테이션의 메타데이터 매개변수를 설정할 수 있습니다. 각 어노테이션을 클래스, 메소드 또는 유형에 적용할 수 있습니다. 이름이 제공되지 않으면 이름은 메소드/생성자 이름에서 가져옵니다.
@Counted
카운터로 메소드, 생성자 또는 유형을 표시하기 위한 어노테이션. 메타데이터 필드와 함께 카운터에도 추가적인 monotonic 필드가 있습니다. monotonic이 false로 설정되면 카운터는 어노테이션이 있는 메소드가 호출될 때마다 증가하고 어노테이션이 있는 메소드가 리턴될 때마다 감소되어 어노테이션이 있는 현재 호출 수를 계수합니다. monotonic이 true로 설정되면 카운터는 단조롭게 증가하여 어노테이션이 있는 메소드의 총 호출 수를 계수합니다.
참고: 기본적으로 monotonic은 false로 설정됩니다.
@GET
@Path("/no")
@Counted(name="no", displayName="No donation count", description="Number of people that declined to donate.", monotonic=true)
public String noDonation() {
    return "Maybe next time!";
}
@Timed
timed로 어노테이션이 있는 오브젝트의 생성자 또는 메소드를 표시하기 위한 어노테이션. 타이머 메트릭은 어노테이션이 있는 오브젝트의 시작 빈도와 호출을 완료하는 데 소요되는 시간을 추적합니다.
@POST
@Path("/creditcard")
@Timed(
    name="donateAmountViaCreditCard.timer",
    displayName="Donations Via Credit Cards",
    description = "Donations that were made using a credit card")
public String donateAmountViaCreditCard(@FormParam("amount") Long amount, @FormParam("card") String card) {
 
    if (processCard(card, amount))
        return "Thanks for donating!";
 
    return "Sorry, please try again.";
 
}
@Metered
metered로 생성자 또는 메소드를 표시하기 위한 어노테이션. 미터는 생성자 또는 메소드의 호출을 계수하고 호출되는 빈도를 추적합니다.
@Metered(displayName="Rate of donations", description="Rate of incoming donations (the instances not the amount)")
public void addDonation(Long amount) {
    totalDonations += amount;
    donations.add(amount);
    donationDistribution.update(amount);
}
@Gauge
gauge로 메소드를 표시하기 위한 어노테이션.
@Gauge(
    name="donations",
    displayName="Total Donations",
    description="Total amount of money raised for charity!",
    unit = "dollars",
    absolute=true)
public Long getTotalDonations(){
    return totalDonations;
}
[18.0.0.1 and later]
메트릭 재사용
MicroProfile 메트릭 버전 1.1 이상을 사용하는 경우 메트릭을 재사용할 수 있습니다. @Counted, @Metered@Timed 어노테이션에는 다른 어노테이션으로 메트릭을 재사용할 수 있음을 표시하는 플래그가 있습니다. 예를 들어, 애플리케이션에는 여러 지불 방법에 대한 다중 엔드포인트가 있을 수 있습니다. 모든 지불 방법 전체에서 지불의 수를 추적하기 위해 reusable=true를 설정하여 같은 메트릭 이름을 사용할 수 있습니다. 다음 예제는 샘플 사용에 대해 설명합니다.
@POST
@Path("/creditcard")
@Counted(
    name="donation.counter",
    displayName="Number of donations",
    description = "Donations that were made using any method",
    monotonic=true,
    reusable=true)
public String donateAmountViaCreditCard(@FormParam("amount") Long amount, @FormParam("card") String card) {
 
    if (processCard(card, amount))
        return "Thanks for donating!";
 
    return "Sorry, please try again.";
 
}
@POST
@Path("/debitcard")
@Counted(
    name="donations.counter",
    displayName="Number of donations",
    description = "Donations that were made using any method",
    monotonic=true,
    reusable=true)
public String donateAmountViaDebitCard(@FormParam("amount") Long amount, @FormParam("card") String card) {
 
    if (processDebitCard(card, amount))
        return "Thanks for donating!";
 
    return "Sorry, please try again.";
 
}

CDI 팁

mpMetrics-1.0 기능은 CDI에 의존합니다. CDI 인젝션은 MetricRegistry를 삽입하거나 메트릭 유형 중 하나를 필드에 삽입하려고 할 때마다 사용됩니다. CDI 인터셉터는 유형, 생성자 또는 메소드 주변에 @Timed, @Counted, @Metered@Gauge 메트릭을 적용하는 데 사용됩니다.

명시적 Bean 아카이브 사용
애플리케이션 시작 효율성을 위해 Bean 아카이브에 beans.xml 파일이 있는지 확인하십시오. 웹 애플리케이션을 작성하는 경우, beans.xml 파일은 WEB-INF 디렉토리에 있습니다. EJB 모듈 또는 JAR 파일을 작성하는 경우, beans.xml 파일은 META-INF 디렉토리에 있습니다. 애플리케이션에 CDI 내재적 Bean 아카이브 기능을 사용하지 않으면 시작 시 Bean 아카이브를 스캔하지 않도록 Liberty 서버를 조정할 수 있습니다.
@Timed, @Counted, @Metered, @Gauge 인터셉터에 대한 제한사항
CDI는 인터셉터로 Liberty에서 구현되는 메트릭 어노테이션에 대한 Java 인터셉터에 의존합니다. @Timed, @Counted, @Metered@Gauge 어노테이션은 인터셉터를 사용하여 구현됩니다. 인터셉터는 프록시가 인터셉터 어노테이션을 사용하여 생성자 또는 메소드를 호출하기 전에 코드 경로에서 시작될 수 있는 프록시를 작성할 수 있다는 것에 의존합니다. 인터셉터 코드는 메트릭이 업데이트되는 위치입니다. 프록시될 수 있는 코드 종류와 인터셉터 어노테이션을 사용할 수 있는 위치에 대한 제한사항이 있습니다. CDI에서 정의된 대로 프록시될 수 있는 관리 Bean만 인터셉터와 함께 사용할 수 있습니다. 프록시는 프록시되는 Bean의 서브클래스로 구현됩니다. 클래스를 프록시할 수 있는지 확인하려면 클래스는 최종으로 표시되면 안 되고 비개인, 비인수 생성자여야 합니다.
인젝션에 대한 제한사항
MetricRegistry와 같은 @Inject 유형을 클래스에 삽입하려면 CDI에서 해당 클래스를 관리해야 합니다. 다음 JAX-RS 예제는 CDI에서 자동으로 호출되는 someclass.setMetricsRegistry에 대해 설명합니다.
@Path("/myPath")
public class MyService {
    // lifecyle of Someclass will be managed by CDI
    @Inject
    Someclass someclass;
 
    ...
}
 
public class Someclass {
    // Someclass was injected and is managed by CDI and therefore can use @Inject
    // setMetricRegistry will be called before the first method call to Someclass
    @Inject
    public void setMetricRegistry(final MetricRegistry metrics) {
    }
}
클래스는 다음 예제에서 호출되지 않습니다.
@Path("/myPath")
public class MyService {
    // CDI doesn't manage lifecycle of Someclass
    Someclass someclass = new Someclass();
 
    ...
}
 
public class Someclass {
    // This method will never be called by CDI since Someclass was not created with CDI
    @Inject
    public void setMetricRegistry(MetricRegistry metrics) {
    }
}

주제의 유형을 표시하는 아이콘 개념 주제

파일 이름: cwlp_mp_metrics_api.html