# 16.3.3 注册自定义指标

在第 16.2.4 节，我们介绍了如何发送 HTTP 请求，获取 `/metrics` 端点的数据，以使用 Actuator 发布的各种指标。Actuator 提供的指标非常有用，但是并不仅限于这些内置的度量指标。

其实，Actuator 指标由 Micrometer 实现 <https://micrometer.io/>。这是一种与供应商无关的度量，使应用程序能够发布任何想要的指标，并将其显示在第三方监控系统中。包括对 Prometheus、Datadog 和 New Relic 等的支持。

使用 Micrometer 发布度量的最基本方法是，使用 Micrometer 的 MeterRegistry。在 Spring Boot 应用程序中，当需要发布计数器、计时器或其他指标时，您只需发布指标到 MeterRegistry 中。

作为发布自定义度量的示例，假设您希望知道，有多少玉米卷用不同的配料制作出来了。就是，您想知道有多少玉米卷是用莴苣、牛肉或土豆或其他配料作成的。下面的清单显示了，TacoMetrics 是如何使用 MeterRegistry 收集这些信息的。

{% code title="程序清单 16.6 TacoMetrics 注册有关玉米卷配料的指标" %}

```java
package tacos.tacos;
import java.util.List;
import
org.springframework.data.rest.core.event.AbstractRepositoryEventListener;
import org.springframework.stereotype.Component;
import io.micrometer.core.instrument.MeterRegistry;

@Component
public class TacoMetrics extends AbstractRepositoryEventListener<Taco> {
  private MeterRegistry meterRegistry;
  public TacoMetrics(MeterRegistry meterRegistry) {
    this.meterRegistry = meterRegistry;
  }

  @Override
  protected void onAfterCreate(Taco taco) {
    List<Ingredient> ingredients = taco.getIngredients();
    for (Ingredient ingredient : ingredients) {
      meterRegistry.counter("tacocloud",
        "ingredient", ingredient.getId()).increment();
    }
  }
}
```

{% endcode %}

如您所见，TacoMetrics 通过其构造函数注入 MeterRegistry。它还扩展了 AbstractRepositoryEventListener，支持拦截存储库事件并重写了 `onAfterCreate()` 方法。这样就可以在保存新的 Taco 对象时随时获取事件通知。

在 `onAfterCreate()` 方法中，为每种配料声明一个计数器，名称为 ingredient ，标签值等于 ingredient 的 ID。如果计数器标记已存在，将重新使用，使计数值递增，这表示另一个玉米卷已经为这种配料添加过标识。

创建了几个 taco 之后，就可以开始查询 `/metrics` 端点了。对 `/metrics/tacocloud` 发关 GET 请求，会产生一些未过滤的度量计数：

```
$ curl localhost:8087/actuator/metrics/tacocloud
{
  "name": "tacocloud",
    "measurements": [ { "statistic": "COUNT", "value": 84 }
  ],
  "availableTags": [
    {
      "tag": "ingredient",
      "values": [ "FLTO", "CHED", "LETC", "GRBF",
                  "COTO", "JACK", "TMTO", "SLSA"]
    }
  ]
}
```

measurements 下的计数值在这里意义不大，因为它是计算所有配料的所有数据的总和。但假设您想知道有多少玉米卷由玉米面制成（FLTO），您需要做的就是指定成分值为 FLTO 的标记：

```
$ curl localhost:8087/actuator/metrics/tacocloud?tag=ingredient:FLTO
{
  "name": "tacocloud",
  "measurements": [
    { "statistic": "COUNT", "value": 39 }
  ],
  "availableTags": []
}
```

现在很明显，39 个玉米卷的配料是玉米面。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://potoyang.gitbook.io/spring-in-action-v5/di-16-zhang-shi-yong-springboot-actuator/16.3-zi-ding-yi-actuator/16.3.3-zhu-ce-zi-ding-yi-zhi-biao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
