spring boot metrics使用指南

spring boot metrics是什麼?

針對應用監控指標暴露,spring boot有一套完整的解決方案,而且內置了好不少的指標收集器,如tomcat、jvm、cpu、kafka、DataSource、spring mvc(缺乏直方圖的數據)等。基於micrometer技術,幾乎支持全部主流的監控服務的指標數據收集,這其中就包含了咱們線上使用的Prometheus,這份指南旨在最快速接入boot的metrics功能,暴露prometheus的數據監控指標服務。web

micrometer地址:https://micrometer.io/spring

1、引入依賴

implementation ('org.springframework.boot:spring-boot-starter-actuator')
implementation ('io.micrometer:micrometer-registry-prometheus:1.6.1')
implementation ('io.micrometer:micrometer-core:1.6.1')

actuator是spring boot中負責運維功能的包,這裏主要是經過它來暴露和管理metrics接口的。其餘兩個依賴是爲了包兼容引入的,在sprinr boot2.x中,actuator中默認引入的prometheus支持包存在兼容性問題,若是你的環境不存在兼容性問題,能夠不用引入下面兩個依賴。api

2、配置啓用

經過以下的配置,來開啓prometheus的端點接口服務瀏覽器

management.endpoints.web.exposure.include=prometheus

開啓服務後,會暴露/actuator/prometheus 端點接口服務。在瀏覽器中,輸入http://localhost:8080/actuator/prometheus 。能夠看到內置的指標收集器收集到的監控指標tomcat

3、獨立的web服務

默認狀況下,/actuator/prometheus端點服務跟隨應用的web容器一塊兒發佈,可是當咱們的web服務面向公網須要受權認證時,可使用以下配置啓用獨立的容器暴露服務mvc

management.server.port=8081

4、全局標籤設置

在metrics監控系統設計中,tag用來標記區分一組指標集。好比咱們在監控grpc時,servicename就是是監控指標的其中一個tag。有的時候爲了區分環境和應用,咱們會設置一些全局的tag:app

management.metrics.tags.application = ${spring.application.name}
management.metrics.tags.region = bj

如上配置,咱們添加了一個應用的名字和一個區域的tag。這種配置是全局的。雖然grpc的組件可能只記錄了servicename,可是最終數據呈現時,也會帶上全局配置的tag運維

5、自定義指標收集

spring boot全部的指標最終都是經過MeterRegistry來註冊的,這個實例被spring託管,因此你能夠在spring的上下文中注入這個實例,結合micrometer指標定義(點我),自定義本身的監控指標jvm

6、推送or拉取指標

目前,咱們線上是經過k8s的monitoring.coreos.com/v1 api定義指定prometheus主動拉取應用pod的監控指標信息,主要是由於以前的metrics系統是基於prometheus client模式暴露的。在基於spring boot的metrics系統中,主動推送數據的模式很是容易實現,這裏須要prometheus-gateway支持spring-boot

引入依賴

implementation("io.prometheus:simpleclient_pushgateway")

啓用push模式

#開啓prometheus的數據推送模式
management.metrics.export.prometheus.pushgateway.enabled=true
#prometheus服務端地址
management.metrics.export.prometheus.pushgateway.base-url=localhost:9091
#推送數據的頻率,默認1m(單位分鐘)
management.metrics.export.prometheus.pushgateway.push-rate=1m
#在jvm關閉以前將數據推送出去
management.metrics.export.prometheus.pushgateway.shutdown-operation=push
相關文章
相關標籤/搜索