使用 Prometheus 和 Grafana 监控 Spring Boot 应用

2024-09-05 09:48

本文主要是介绍使用 Prometheus 和 Grafana 监控 Spring Boot 应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用 Prometheus 和 Grafana 监控 Spring Boot 应用

监控 Spring Boot 应用的状态,以及一些自定义的业务数据

监控 Spring Boot 应用

  • 添加依赖 build.gradle
    compile('org.springframework.boot:spring-boot-starter-actuator')compile('io.micrometer:micrometer-core:1.5.1')compile('io.micrometer:micrometer-registry-prometheus:1.5.1')
  • 修改配置 application.properties

需要注意的是,management.metrics.tags.application这个参数一定要有,否则很多报表会因为没有这个tag不能正常显示

# Actuator
management.endpoints.web.exposure.include=*
# Prometheus
management.metrics.tags.application=${spring.application.name}
  • 添加 Prometheus 监控
- job_name: 'spring-prometheus'metrics_path: '/actuator/prometheus'scrape_interval: 5sstatic_configs:- targets:- host.docker.internal:8081
  • 配置 Grafana

从 Grafana Dashboard 市场查找 Spring Boot 的看板,复制 ID 导入到 Grafana 中,如 6756

导入之后发现有些数据不能正确显示,这是因为设置了变量,需要修改变量的值:

Dashboard Setting -> Variables,选择相应的变量进行修改,这里修改两个:applicaitoninstance

application

label_values(application)

instance

label_values(jvm_memory_used_bytes{application="$application"},instance)

springboot-grafana-dashboard-variable.png

这样,就可以实现 application 和 instance的联动,选择application后,instance中显示相应的应用的实例

springboot-grafana-dashboard.png

监控方法执行时间和数量

Prometheus 提供了时间和数量的监控指标,通过在定时任务上添加 @Counted@Timed来监控数据;相关文档可以参考 The @Timed annotation

  • 注入切面的Bean
@EnableAspectJAutoProxy
@Configuration
public class PrometheusAspectConfig {@Beanpublic TimedAspect timedAspect(MeterRegistry registry) {return new TimedAspect(registry);}@Beanpublic CountedAspect countedAspect(MeterRegistry registry) {return new CountedAspect(registry);}
}
监控定时任务
  • 监控定时任务
@Slf4j
@Component
public class CustomScheduleTask {private static final Random random = new Random();@Scheduled(fixedDelay = 5000)@Timed(value = "custom_task_time", extraTags = {"name", "自定义定时任务"}, description = "自定义定时任务监控")public void customSchedule() throws InterruptedException {Thread.sleep(random.nextInt(5000));log.info("定时任务执行完成");}
}
  • 查看监控数据
curl localhost:8081/actuator/prometheus | grep custom_task
监控接口
  • controller
    @Timed@Counted@GetMapping("/timed")public Object timed() throws InterruptedException {return customService.timed(UUID.randomUUID().toString());}
  • 监控数据
curl localhost:8081/actuator/prometheus | grep method_time

自定义监控指标

通过自定义监控指标监控业务相关数据

监控类型

相关监控类型的文档可以参考 Metrics types
相关使用文档可以参考 Prometheus JVM Client

  • Counter

一个单调递增的累计计量,在重新启动时值会被置为0,可以用于统计请求数量,错误数量,任务完成的数量等;不能用Counter统计可以减少的值

  • Gauge

Gauge 表示可以任意增减的值,通常用于计量类似温度,CPU使用率这样的值,或者正在处理的请求数量这样可增可减的值

  • Histogram

统计直方图,通常用于统计请求的时间,响应body的大小等,并将其计数在可配置的存储桶中,它还提供所有观察值的总和

  • Summary

和 Histogram 类似,它在滑动时间窗口内计算可配置的分位数,详细区别可以参考 Histograms and summaries

自定义监控请求统计

添加统计数据

定义统计请求数据,分别统计请求的次数,错误的次数,相应的时间;可以使用 Filter来实现

@Component
@Slf4j
public class AccessMetricsFilter implements Filter {@Autowiredprivate CollectorRegistry collectorRegistry;@Value("${spring.application.name}")private String applicationName;private Counter totalCounter;private Counter errorCounter;private Histogram responseTime;@PostConstructprivate void init() {log.info("初始化counter");totalCounter = Counter.build("custom_request_total", "自定义请求次数统计").labelNames("application", "path").create();errorCounter = Counter.build("custom_request_error", "自定义请求错误次数统计").labelNames("application", "path").create();responseTime = Histogram.build("custom_response_time", "自定义请求响应时间").labelNames("application", "path").create();collectorRegistry.register(totalCounter);collectorRegistry.register(errorCounter);collectorRegistry.register(responseTime);}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();String path = request.getRequestURI();Histogram.Timer timer = responseTime.labels(applicationName, path).startTimer();try {filterChain.doFilter(servletRequest, servletResponse);} catch (Exception e) {errorCounter.labels(applicationName, path).inc();throw e;} finally {totalCounter.labels(applicationName, path).inc();timer.observeDuration();}}
}
  • 启动应用,访问接口后查看统计数据
curl localhost:8081/actuator/prometheus | grep custom_request# HELP custom_request_total 自定义请求次数统计
# TYPE custom_request_total counter
custom_request_total{path="/order",} 3.0
custom_request_total{path="/db",} 1004.0
custom_request_total{path="/actuator/prometheus",} 150.0
# HELP custom_request_error 自定义请求错误次数统计
# TYPE custom_request_error counter
添加监控看板
  • 现在要统计所有的错误请求次数,可以在 Prometheus的查询面板中查询:

springboot-custom-metrics-prometheus.png

这样,就可以得到相应的错误数据,接下来只需要在Grafana中展示就可以

  • 添加看板

添加一个 Dashboard,并添加一个 Panel,在 Panel 的 Metrics 中添加刚才的查询语句

springboot-custom-metrics-grafana-query.png

执行查询后,会看到有图表生成,变量的名称通过 Legend 字段指定,如这里是 custom_request_total{application="prometheus", instance="host.docker.internal:8081", job="spring-prometheus", path="/db"},需要显示路径名称,即 path 的值,可以设置 Legend 为 {{path}},这样会显示正确的名称

其他的显示单位,显示效果等以及面板的名称可以通过旁边的设置选项进行配置

prometheus-grafana-custom-dashboard-setting-panel-detail.png

  • 添加应用和实例变量

Dashboard Settings -> Variables

label_values(application)label_values(jvm_memory_used_bytes{application="$application"},instance)
  • 添加统计数据查询
# 请求总次数
sum(custom_request_total{application="$application",instance="$instance"})# 错误请求总次数
sum(custom_request_total{application="$application", instance="$instance"})# 每分钟请求次数
rate(custom_request_total{application="$application", instance="$instance"}[1m])# 每分钟错误请求次数
rate(custom_request_error{application="$application", instance="$instance"}[$__interval])

prometheus-grafana-custom-dashboard-result.png


  • 相关项目可以参考 Prometheus

这篇关于使用 Prometheus 和 Grafana 监控 Spring Boot 应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.