使用 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

相关文章

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

SpringBoot整合liteflow的详细过程

《SpringBoot整合liteflow的详细过程》:本文主要介绍SpringBoot整合liteflow的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...  liteflow 是什么? 能做什么?总之一句话:能帮你规范写代码逻辑 ,编排并解耦业务逻辑,代码

JavaSE正则表达式用法总结大全

《JavaSE正则表达式用法总结大全》正则表达式就是由一些特定的字符组成,代表的是一个规则,:本文主要介绍JavaSE正则表达式用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录常用的正则表达式匹配符正则表China编程达式常用的类Pattern类Matcher类PatternSynta

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁