Spring Boot 自 2.0.0 开始, 全面使用 micrometer instrumentation library(io.io.micrometer) 作为应用指标抓取实现。

Spring Actuator 原理 应用可通过 metrics 端口获取全部内置监控指标

应用团队通常喜欢使用 Netflix Altas, Google Prometheus, Datadog 等第三方平台实现指标收集,然后通过 grafana 等可视化平台进行监控展示。

Spring Boot 并没有内置指标收集平台客户端,但提供了充分的拓展能力,允许对应平台包将 spring metrics 转化为对应平台格式的 metrics。

以 prometheus 为例,Spring Boot 内置了转换,因此只需要加入以下包,即可开启一个支持 prometheus 的 actuator endpoint。

文档 https://docs.spring.io/spring-metrics/docs/current/public/prometheus 提供了 datadog, altas 的集成。

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

类似的,通过 micrometer-registry-* 等系列包,即可轻松转换指标到对应平台。

Spring Cloud 微服务监控

Spring Cloud 环境下,服务数量巨多,通过 prometheus 逐应用配置监控接口并不显示,这时候可以利用注册中心作为中转进行批量获取。目前 prometheus 只有 Consul 支持而没有提供 Eureka 支持,因此可以引入一个 Eureka-Consul 适配器解决问题。

#[<https://github.com/twinformatics/eureka-consul-adapter/tree/1.3.0>](<https://github.com/twinformatics/eureka-consul-adapter/tree/1.3.0>)
compile 'at.twinformatics:eureka-consul-adapter:${eureka-consul-adapter.version}'

引入之后,Eureka 服务会有 3 个与 Consul 相同的接口供 prometheus 获取

/v1/agent/self Returns the name of the datacenter in use (Consul API: <https://www.consul.io/api/agent.html#read-configuration>). In Eureka, this can be set using the archaius.deployment.datacenter configuration property.
/v1/catalog/services Returns the names of the deployed applications (Consul API: <https://www.consul.io/api/catalog.html#list-services>). No service tags service will be returned as Eureka does not support this concept.
/v1/catalog/service/{service} Returns all available details for the particular application (instances, host names, ports, meta data, service tags). No service tags service will be returned as Eureka does not support this concept.

/v1/catalog/service/{service}

[
    {
        "Address": "10.152.1.145",
        "Node": "OPENAPI-SERVICE-BASE-API-GATEWAY",
        "ServiceAddress": "10.152.1.145",
        "ServiceID": "ip-10-152-1-145.cn-north-1.compute.internal:openapi-service-base-api-gateway:7100",
        "ServicePort": 7100,
        "NodeMeta": {
            "management.port": "7100"
        },
        "ServiceTags": []
    }
]

在 prometheus 配置 job 之后,prometheus 即可利用注册中心获取应用信息,再从对应应用拉取监控指标

- job_name: "eureka-zx"
    consul_sd_configs:
    - server: "10.152.1.161:7000"
    metrics_path: /actuator/prometheus

grafana 展示

grafana 集成 promethus 也是配置一个 url 的事 https://grafana.com/docs/features/datasources/prometheus/