spring boot 项目 prometheus 自定义指标收集区分应用环境集群实例ip,使用 grafana 查询--方法耗时分位数指标

本文主要是介绍spring boot 项目 prometheus 自定义指标收集区分应用环境集群实例ip,使用 grafana 查询--方法耗时分位数指标,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

spring boot 项目 prometheus 自定义指标收集

auth

  1. @author JellyfishMIX - github / blog.jellyfishmix.com
  2. LICENSE LICENSE-2.0

说明

  1. 网上有很多 promehteus 和 grafana 配置,本文不再重复,只介绍自定义部分。
  2. 目前只介绍了分位数指标的收集和查询,常用于方法耗时的指标监控。

自定义指标收集

仅引入以下依赖,只能看到 spring actuator 相关指标,看不到自定义指标。

            <!-- spring-boot-actuator 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId><version>2.7.18</version></dependency><!-- prometheus 依赖,和 spring boot 版本需要搭配。spring boot 2.7 搭配 1.10.x 如需升级或降级 spring boot,可以对应 +- 0.1.0--><dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId><version>1.10.6</version></dependency>

application.properties 配置

根据需要自定义调整

spring.application.name=spring-boot-explore
server.port=8083
server.servlet.context-path=/explore
# ip:port/actuator/prometheus
management.server.port=9051
management.endpoints.web.exposure.include=*
management.metrics.tags.application=${spring.application.name}

自定义指标的收集需要引入额外依赖

            <!--自定义 prometheus 指标依赖--><dependency><groupId>io.prometheus</groupId><artifactId>simpleclient</artifactId><version>0.16.0</version></dependency><dependency><groupId>io.prometheus</groupId><artifactId>simpleclient_hotspot</artifactId><version>0.16.0</version></dependency><dependency><groupId>io.prometheus</groupId><artifactId>simpleclient_servlet</artifactId><version>0.16.0</version></dependency>

指标收集接口

按照 prometheus 的约定,客户端需要暴露一个接口供收集自定义指标。

import io.prometheus.client.exporter.MetricsServlet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author jellyfishmix* @date 2024/9/1 08:03*/
@Controller
@RequestMapping("/prometheus")
public class PrometheusExportController extends MetricsServlet {@RequestMapping("/exportMetric")@ResponseBodypublic void exportMetric(HttpServletRequest request, HttpServletResponse response) throws IOException {this.doGet(request, response);}
}

暴露后的自定义指标收集端口,路径是自己配置的:

image-20240901103532161

自定义指标示例

    private static final Counter DEMO_COUNTER = Counter.build().name("TestController_compute_counter_demo").help("demo of counter").labelNames("labelName1", "labelNameB").namespace("spring_boot_explore").register(DEFAULT_PROMETHEUS_REGISTRY);
namespace 方法

定义指标的前缀,不能包含中划线-,实际指标会带上 namespace 前缀,namespace 与 name 中间自动被下划线_拼接。

spring_boot_explore_TestController_compute_counter_demo
labelNames 方法

使用哦 Summary 举例,说明一下 Counter.build().labelNames() 方法,表示为此指标设置两个 label,分别命名为 labelName1 和 labelNameB。

.labelNames("labelName1", "labelNameB")

如果设置了 Counter.build().labelNames(),不能直接调用 counter.inc(),会抛 NullPointerException

// Convenience methods./*** Increment the counter with no labels by the given amount.** @throws IllegalArgumentException If amt is negative.*/public void inc(double amt) {noLabelsChild.inc(amt);}

需要调用 summary.labels(“abc”, “123”).observe(),labels 方法中的值表示构造 summary 指标时对应的 labelName 的值。

    @RequestMapping("/sayCounter")@ResponseBodypublic String sayCounter() {DEMO_COUNTER.labels("abc", "123").inc(1);return "hello summary";}

自定义指标区分应用、环境、集群、实例

记录指标的接口

通过 .namespace 和 .labelNames 区分 env 环境名, cluster 集群名, instance 实例信息(一般为ip)

import com.google.common.base.Stopwatch;
import com.jellyfishmix.springbootexplore.server.config.PropertiesLoader;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Summary;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;@RequestMapping("/test")
@Controller
public class TestController {private static final CollectorRegistry DEFAULT_PROMETHEUS_REGISTRY = CollectorRegistry.defaultRegistry;private static final String applicationName = PropertiesLoader.getProperty("spring.application.name");private static final String env = PropertiesLoader.getProperty("custom.application.env");private static final String cluster = PropertiesLoader.getProperty("custom.application.cluster");private static final Counter DEMO_COUNTER = Counter.build().name("TestController_compute_counter_demo").help("demo of counter")// env 环境名, cluster 集群名, instance 实例信息(一般为ip).labelNames("env", "cluster", "instance")// namespace 应用名.namespace(applicationName).register(DEFAULT_PROMETHEUS_REGISTRY);private static String instance = getLocalIpAddress();public static String getLocalIpAddress() {try {InetAddress localHost = InetAddress.getLocalHost();return localHost.getHostAddress();} catch (UnknownHostException e) {e.printStackTrace();return StringUtils.EMPTY;}}@RequestMapping("/sayCounter")@ResponseBodypublic String sayCounter() {// 对应 .labelNames 中的 env 环境名, cluster 集群名, instance 实例信息(一般为ip)DEMO_COUNTER.labels(env, cluster, instance).inc(1);return "hello counter";}
}

application.properties 配置,注意 prometheus 指标 namespace 不能用-,需要用_

spring.application.name=spring_boot_explore
custom.application.env=beta
custom.application.cluster=cluster_master
server.port=8083
server.servlet.context-path=/explore

由于 properties 配置无法通过 @Value 在静态方法/字段获取值,因此需要手动加载配置文件来获取 properties 值。

import org.apache.commons.lang3.StringUtils;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;/*** @author jellyfishmix* @date 2024/9/1 18:45*/
public class PropertiesLoader {private static Map<String, String> propertiesMap = new LinkedHashMap<>();/*** jvm 启动参数中指定 active profile*/private static final String ACTIVE_PROFILE_JVM_ARG_KEY_WORD = "spring.profiles.active=";static {load("application.properties");String activeProfile = null;// 先检查 jvm active profilevar jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();for (String arg : jvmArgs) {if (arg.contains(ACTIVE_PROFILE_JVM_ARG_KEY_WORD)) {int index = arg.indexOf("=");if (index!= -1) {activeProfile = arg.substring(index + 1);}break;}}// jvm 参数未指定 active profile,再尝试使用 application.properties 中指定的if (StringUtils.isEmpty(activeProfile)) {activeProfile = propertiesMap.get("spring.profiles.active");}if (StringUtils.isNotBlank(activeProfile)) {load("application-" + activeProfile + ".properties");}}public static void load(String fileName) {final Properties properties = new Properties();FileInputStream fis = null;InputStream is = null;// 两种加载方式,第一种根据文件路径加载try {fis = new FileInputStream(fileName);properties.load(fis);} catch (Throwable ignored) {// 如果失败了,使用类加载器去 classpath 加载try {final ClassLoader classLoader = PropertiesLoader.class.getClassLoader();is = classLoader.getResourceAsStream(fileName);properties.load(is);} catch (Exception ex) {// can record logreturn;}} finally {try {if (fis != null) {fis.close();}if (is != null) {is.close();}} catch (Throwable ignored) {// do nothing}}propertiesMap.putAll(new LinkedHashMap<String, String>((Map) properties));}public static String getProperty(String key) {return propertiesMap.get(key);}
}

区分应用,环境,集群的效果

image-20240901214356871

分位数指标

  1. prometheus 四种 metrics 类型中,如果不是对性能特别敏感的场景,推荐使用 summary。详情阅读:
    1. summary 和 histogram 指标的简单理解 https://blog.csdn.net/wtan825/article/details/94616813
    2. prometheus 四种 metric 类型介绍 https://prometheus.wang/promql/prometheus-metrics-types.html

使用 summary 监控方法耗时

import com.google.common.base.Stopwatch;
import com.jellyfishmix.springbootexplore.server.config.PropertiesLoader;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Summary;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;/*** @author jellyfishmix* @date 2024/1/3 23:18*/
@RequestMapping("/test")
@Controller
public class TestController {private static final CollectorRegistry DEFAULT_PROMETHEUS_REGISTRY = CollectorRegistry.defaultRegistry;private static final Summary DEMO_SUMMARY = Summary.build().name("TestController_compute_summary_demo").help("demo of summary").labelNames("labelName1", "labelNameB").quantile(0.5, 0.01).quantile(0.90, 0.01).quantile(0.99, 0.01).register(DEFAULT_PROMETHEUS_REGISTRY);@RequestMapping("/saySummary")@ResponseBodypublic String saySummary() {Stopwatch stopwatch = Stopwatch.createStarted();simulateInterfaceCall();var costMillis = stopwatch.elapsed().toMillis();DEMO_SUMMARY.labels("abc", "123").observe(costMillis);return "hello summary";}private static void simulateInterfaceCall() {// 模拟接口调用的随机耗时int randomDelay = ThreadLocalRandom.current().nextInt(100, 1000);try {TimeUnit.MILLISECONDS.sleep(randomDelay);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}
}
quantile 方法
  1. 说明一下 Summary.build().quantile() 方法。
  2. .50 分位,误差 0.01,会把 [.49, .51] 范围内的指标计入 .50 分位,由于 summary 会在客户端把指标数记录下来,因此允许的误差越多,可以节约的内存占用越多。
  3. 其他分位以此类推。
# .50 分位,误差 0.01
.quantile(0.5, 0.01)
# .90 分位,误差 0.01
.quantile(0.90, 0.01)
# .99 分位,误差 0.01
.quantile(0.99, 0.01)

quantile 方法的详细说明可见 io.prometheus.client.Summary 的类注释,这里摘抄一段:

The Summary class provides different utility methods for observing values, like observe(double), startTimer() and Summary. Timer. observeDuration(), time(Callable), etc.
By default, Summary metrics provide the count and the sum. For example, if you measure latencies of a REST service, the count will tell you how often the REST service was called, and the sum will tell you the total aggregated response time. You can calculate the average response time using a Prometheus query dividing sum / count.
In addition to count and sum, you can configure a Summary to provide quantiles:Summary requestLatency = Summary. build().name("requests_latency_seconds").help("Request latency in seconds.").quantile(0.5, 0.01)    // 0.5 quantile (median) with 0.01 allowed error.quantile(0.95, 0.005)  // 0.95 quantile with 0.005 allowed error// ....register();As an example, a 0.95 quantile of 120ms tells you that 95% of the calls were faster than 120ms, and 5% of the calls were slower than 120ms.
Tracking exact quantiles require a large amount of memory, because all observations need to be stored in a sorted list. Therefore, we allow an error to significantly reduce memory usage.
In the example, the allowed error of 0.005 means that you will not get the exact 0.95 quantile, but anything between the 0.945 quantile and the 0.955 quantile.
Experiments show that the Summary typically needs to keep less than 100 samples to provide that precision, even if you have hundreds of millions of observations.

summary 分位数指标效果示例

image-20240901103720431

grafana 视图

grafana query 填写示例如下,注意正确的分位数查询写法是如下图红圈所示,在 metric 位置填写 quantile = 0.5(客户端收集时填写的具体分位数)。

Screenshot 2024-09-01 at 11.41.23

分位数查询错误示例: operations 中填写 quantile 是错误的写法,可以看到图中,通过 operations 计算出的和真实值差距很大。

Screenshot 2024-09-01 at 11.48.24

这篇关于spring boot 项目 prometheus 自定义指标收集区分应用环境集群实例ip,使用 grafana 查询--方法耗时分位数指标的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1129269

相关文章

Linux下如何使用C++获取硬件信息

《Linux下如何使用C++获取硬件信息》这篇文章主要为大家详细介绍了如何使用C++实现获取CPU,主板,磁盘,BIOS信息等硬件信息,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录方法获取CPU信息:读取"/proc/cpuinfo"文件获取磁盘信息:读取"/proc/diskstats"文

Java数组初始化的五种方式

《Java数组初始化的五种方式》数组是Java中最基础且常用的数据结构之一,其初始化方式多样且各具特点,本文详细讲解Java数组初始化的五种方式,分析其适用场景、优劣势对比及注意事项,帮助避免常见陷阱... 目录1. 静态初始化:简洁但固定代码示例核心特点适用场景注意事项2. 动态初始化:灵活但需手动管理代

Java使用SLF4J记录不同级别日志的示例详解

《Java使用SLF4J记录不同级别日志的示例详解》SLF4J是一个简单的日志门面,它允许在运行时选择不同的日志实现,这篇文章主要为大家详细介绍了如何使用SLF4J记录不同级别日志,感兴趣的可以了解下... 目录一、SLF4J简介二、添加依赖三、配置Logback四、记录不同级别的日志五、总结一、SLF4J

将Java项目提交到云服务器的流程步骤

《将Java项目提交到云服务器的流程步骤》所谓将项目提交到云服务器即将你的项目打成一个jar包然后提交到云服务器即可,因此我们需要准备服务器环境为:Linux+JDK+MariDB(MySQL)+Gi... 目录1. 安装 jdk1.1 查看 jdk 版本1.2 下载 jdk2. 安装 mariadb(my

使用Python实现一个优雅的异步定时器

《使用Python实现一个优雅的异步定时器》在Python中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

基于Python实现读取嵌套压缩包下文件的方法

《基于Python实现读取嵌套压缩包下文件的方法》工作中遇到的问题,需要用Python实现嵌套压缩包下文件读取,本文给大家介绍了详细的解决方法,并有相关的代码示例供大家参考,需要的朋友可以参考下... 目录思路完整代码代码优化思路打开外层zip压缩包并遍历文件:使用with zipfile.ZipFil

如何使用Nginx配置将80端口重定向到443端口

《如何使用Nginx配置将80端口重定向到443端口》这篇文章主要为大家详细介绍了如何将Nginx配置为将HTTP(80端口)请求重定向到HTTPS(443端口),文中的示例代码讲解详细,有需要的小伙... 目录1. 创建或编辑Nginx配置文件2. 配置HTTP重定向到HTTPS3. 配置HTTPS服务器

Python处理函数调用超时的四种方法

《Python处理函数调用超时的四种方法》在实际开发过程中,我们可能会遇到一些场景,需要对函数的执行时间进行限制,例如,当一个函数执行时间过长时,可能会导致程序卡顿、资源占用过高,因此,在某些情况下,... 目录前言func-timeout1. 安装 func-timeout2. 基本用法自定义进程subp

SpringBoot中配置Redis连接池的完整指南

《SpringBoot中配置Redis连接池的完整指南》这篇文章主要为大家详细介绍了SpringBoot中配置Redis连接池的完整指南,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以... 目录一、添加依赖二、配置 Redis 连接池三、测试 Redis 操作四、完整示例代码(一)pom.

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思