SmallRye Metrics

以下指南演示了 Quarkus 应用程序如何使用 SmallRye Metrics,这是 MicroProfile Metrics规范的实现。

The following guide demonstrates how a Quarkus application can use SmallRye Metrics, an implementation of the MicroProfile Metrics specification.

SmallRye Metrics 允许应用程序收集指标和统计数据,这些数据提供了有关应用程序内部发生的事情的见解。可以远程使用 JSON 或 OpenMetrics 格式读取指标信息,供 Prometheus 等其他工具处理并存储以进行分析和可视化。

SmallRye Metrics allows applications to gather metrics and statistics that provide insights into what is happening inside an application. The metrics can be read remotely using the JSON or OpenMetrics format to be processed by additional tools such as Prometheus and stored for analysis and visualization.

除了本指南中描述的特定于应用程序的指标外,你还可以使用各种 Quarkus 扩展公开的内置指标。这些内容在支持内置指标的每个特定扩展指南中进行了描述。

Apart from application-specific metrics described in this guide, you may also use built-in metrics exposed by various Quarkus extensions. These are described in the guide for each particular extension that supports built-in metrics.

Micrometer是针对 Quarkus 指标的推荐方法。在需要保留 MicroProfile 规范兼容性时,请使用 SmallRye Metrics 扩展。

Micrometer is the recommended approach to metrics for Quarkus. Use the SmallRye Metrics extension when it is required to retain MicroProfile specification compatibility.

当 Quarkus 升级到 Eclipse MicroProfile 6 时,SmallRye Metrics 支持将终止。

When Quarkus will upgrade to Eclipse MicroProfile 6, the SmallRye Metrics support will be discontinued.

Unresolved directive in smallrye-metrics.adoc - include::{includes}/extension-status.adoc[]

Prerequisites

Unresolved directive in smallrye-metrics.adoc - include::{includes}/prerequisites.adoc[]

Architecture

在此示例中,我们构建了一个非常简单的微服务,提供了一个 REST 端点。该端点用于确定一个数是否是素数。实现类带有一些特定的度量注解,以便在响应用户的请求时收集特定的度量信息。稍后解释每个度量指标的含义。

In this example, we build a very simple microservice that offers one REST endpoint. This endpoint serves for determining whether a number is prime. The implementation class is annotated with certain metric annotations so that while responding to users' requests, certain metrics are gathered. The meaning of each metric is explained later.

Solution

我们建议你按照下一节中的说明一步一步创建应用程序。但是,你可以跳到已完成的示例。

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can skip to the completed example.

  1. Clone the Git repository:[source, bash]

git clone {quickstarts-clone-url}
  • Alternatively, download a {quickstarts-archive-url}[Quickstarts archive]. The solution is located in the microprofile-metrics-quickstart directory and follow with the Running and using the application section.

Creating a Maven project

若要创建一个新项目:

To create a new project:

Unresolved directive in smallrye-metrics.adoc - include::{includes}/devtools/create-app.adoc[]

此命令生成一个使用 `smallrye-metrics`扩展的 Quarkus 项目。

This command generates a Quarkus project that uses the smallrye-metrics extension.

如果你已配置好 Quarkus 项目,则可以通过在项目基本目录中运行以下命令,将 `smallrye-metrics`扩展添加到项目中:

If you already have your Quarkus project configured, you can add the smallrye-metrics extension to your project by running the following command in your project base directory:

Unresolved directive in smallrye-metrics.adoc - include::{includes}/devtools/extension-add.adoc[]

这将把以下内容添加到您的构建文件中:

This adds the following to your build file:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-smallrye-metrics</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-smallrye-metrics")

Writing an application

以下过程创建一个 Quarkus 应用程序,该程序包含一个实现用于检查数字是否为素数的算法的类。该算法通过一个 REST 接口公开。此外,需要有特定注解来确保在一段时间内计算出所需的度量信息,并且可以导出该信息以进行手动分析或通过其他工具进行处理。

The following procedures create a Quarkus application that consists of a single class that implements an algorithm for checking whether a number is prime. This algorithm is exposed over a REST interface. Additionally, specific annotations are required to ensure that the desired metrics are calculated over time and can be exported for manual analysis or processing by additional tooling.

该应用程序将收集以下指标:

The application will gather the following metrics:

  • performedChecks: A counter that increases by one each time the user asks about a number.

  • highestPrimeNumberSoFar: A gauge that stores the highest number asked about by the user if the number was determined to be prime.

  • checksTimer: A compound metric that benchmarks how much time the primality tests take. Additional details are provided later.

整个源代码如下所示:

The full source code looks as follows:

package org.acme.microprofile.metrics;

import org.eclipse.microprofile.metrics.MetricUnits;
import org.eclipse.microprofile.metrics.annotation.Counted;
import org.eclipse.microprofile.metrics.annotation.Gauge;
import org.eclipse.microprofile.metrics.annotation.Timed;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("/")
public class PrimeNumberChecker {

    private long highestPrimeNumberSoFar = 2;

    @GET
    @Path("/{number}")
    @Produces(MediaType.TEXT_PLAIN)
    @Counted(name = "performedChecks", description = "How many primality checks have been performed.")
    @Timed(name = "checksTimer", description = "A measure of how long it takes to perform the primality test.", unit = MetricUnits.MILLISECONDS)
    public String checkIfPrime(long number) {
        if (number < 1) {
            return "Only natural numbers can be prime numbers.";
        }
        if (number == 1) {
            return "1 is not prime.";
        }
        if (number == 2) {
            return "2 is prime.";
        }
        if (number % 2 == 0) {
            return number + " is not prime, it is divisible by 2.";
        }
        for (int i = 3; i < Math.floor(Math.sqrt(number)) + 1; i = i + 2) {
            if (number % i == 0) {
                return number + " is not prime, is divisible by " + i + ".";
            }
        }
        if (number > highestPrimeNumberSoFar) {
            highestPrimeNumberSoFar = number;
        }
        return number + " is prime.";
    }

    @Gauge(name = "highestPrimeNumberSoFar", unit = MetricUnits.NONE, description = "Highest prime number so far.")
    public Long highestPrimeNumberSoFar() {
        return highestPrimeNumberSoFar;
    }

}

Running and using the application

要执行在 Writing an application 中创建的应用程序,请执行以下操作:

To execute the application created in Writing an application, do the following:

  1. Run the microservice in dev mode:[.iokays-translated-f19b9e665092a272f1c58e1409b3842e] include::{includes}/devtools/dev.adoc[]:!devtools-wrapped:

Unresolved directive in smallrye-metrics.adoc - include::{includes}/devtools/dev.adoc[] :!devtools-wrapped: . Generate values for the metrics.[style="loweralpha"]

  1. Query the endpoint to determine whether some numbers are prime numbers:[source, bash]

curl localhost:8080/350

应用程序会响应说 350 不是质数,因为它可以被 2 整除。

The application will respond that 350 is not a prime number because it can be divided by 2.

  • For large prime numbers, the test takes more time.[source, bash]

curl localhost:8080/629521085409773

应用程序会响应说 629521085409773 是质数。

The application will respond that 629521085409773 is a prime number.

  1. Perform additional calls with numbers of your choice.

    1. Review the generated metrics:[source, bash]

curl -H"Accept: application/json" localhost:8080/q/metrics/application

您会收到如下响应:

You will receive a response such as:

{
  "org.acme.microprofile.metrics.PrimeNumberChecker.checksTimer" : {			                    1
    "p50": 217.231273,										                                        2
    "p75": 217.231273,
    "p95": 217.231273,
    "p98": 217.231273,
    "p99": 217.231273,
    "p999": 217.231273,
    "min": 0.58961,										                                            3
    "mean": 112.15909190834819,								                                        4
    "max": 217.231273,									                                            5
    "stddev": 108.2721053982776,							    	                                6
    "count": 2,											                                            7
    "meanRate": 0.04943519091742238,							                                    8
    "oneMinRate": 0.2232140583080189,
    "fiveMinRate": 0.3559527083952095,
    "fifteenMinRate": 0.38474303050928976
  },
  "org.acme.microprofile.metrics.PrimeNumberChecker.performedChecks" : 2,		                    9
  "org.acme.microprofile.metrics.PrimeNumberChecker.highestPrimeNumberSoFar" : 629521085409773		10
}
1 checksTimer: A compound metric that benchmarks how much time the primality tests take. All durations are measured in milliseconds. It consists of these values below.
2 p50, p75, p95, p99, p999: Percentiles of the durations. For example, the value in p95 means that 95 % of the measurements were faster than this duration.
3 min: The shortest duration it took to perform a primality test was probably performed for a small number.
4 mean: The mean value of the measured durations.
5 max: The longest duration, probably it was with a large prime number.
6 stddev: The standard deviation.
7 count: The number of observations, the value of which is the same as performedChecks.
8 meanRate, oneMinRate, fiveMinRate, fifteenMinRate: Mean throughput and one-, five-, and fifteen-minute exponentially-weighted moving average throughput.
9 performedChecks: A counter which is increased by one each time the user asks about a number.
10 highestPrimeNumberSoFar: A gauge that stores the highest number that was asked about by the user and which was determined to be prime.

如果您更喜欢 OpenMetrics 导出而不是 JSON 格式,请从命令行中删除 `-H"Accept: application/json"`参数。

If you prefer an OpenMetrics export rather than the JSON format, remove the -H"Accept: application/json" argument from your command line.

Management interface

默认情况下,系统在主 HTTP 服务器上公开规则。您可以通过使用 `quarkus.management.enabled=true`属性启用管理界面在单独的网络接口和端口上公开这些规则。有关详细信息,请参阅 management interface reference

By default, the metrics are exposed on the main HTTP server. You can expose them on a separate network interface and port by enabling the management interface with the quarkus.management.enabled=true property. Refer to the management interface reference for more information.

Configuration Reference

Unresolved directive in smallrye-metrics.adoc - include::{generated-dir}/config/quarkus-smallrye-metrics.adoc[]