Spring Boot进阶(94):从入门到精通:Spring Boot和Prometheus监控系统的完美结合

news/2024/5/19 0:21:55 标签: spring boot, prometheus

📣前言

  随着云原生技术的发展,监控和度量也成为了不可或缺的一部分。Prometheus 是一款最近比较流行的开源时间序列数据库,同时也是一种监控方案。它具有极其灵活的查询语言、自身的数据采集和存储机制以及易于集成的特点。而 Spring Boot 是一款快速构建应用的框架,其提供了大量自动化的配置和功能,使得开发者可以更加专注于业务逻辑的开发,而不必关心大量的配置和环境搭建。

  本文将介绍 Spring Boot 如何集成 Prometheus 进行应用监控,并结合实际应用场景,给出一些使用 Prometheus 监控应用的案例,以及优缺点分析和测试用例。

  那么,具体如何实现呢?这将又会是干货满满的一期,全程无尿点不废话只抓重点教,具有非常好的学习效果,拿好小板凳准备就坐!希望学习的过程中大家认真听好好学,学习的途中有任何不清楚或疑问的地方皆可评论区留言或私信,bug菌将第一时间给予解惑,那么废话不多说,直接开整!Fighting!!

🌊环境说明

开发工具:IDEA 2021.3
JDK版本: JDK 1.8
Spring Boot版本:2.3.1 RELEASE
Maven版本:3.8.2


🏆本文收录于《Spring Boot从入门到精通》,专门攻坚指数提升,2023 年国内最系统+最强(更新中)。

本专栏致力打造最硬核 Spring Boot 从零基础到进阶系列学习内容,🚀均为全网独家首发,打造精品专栏,专栏持续更新中…欢迎大家订阅持续学习。 如果想快速定位学习,可以看这篇【SpringBoot教程导航帖】,你想学习的都被收集在内,快速投入学习!!两不误。


🌊摘要

本文主要介绍如何在 Spring Boot 中集成 Prometheus 进行应用监控,重点讲解以下内容:

  • Prometheus 的概述和优缺点分析
  • Spring Boot 集成 Prometheus 的教学
  • 应用场景案例
  • 实战教学
  • 测试用例
  • 全文小结和结尾

🌊正文


Prometheus 是什么?

Prometheus 是一个开源的系统监控和警报工具包。它实现了完整的数据采集、存储和查询功能,可以帮助开发者对应用的性能和状态进行监控,并提供丰富的查询语言和可视化界面。

Prometheus 具有以下特点:

  • 支持多种数据采集方式,包括 HTTP、JMX、Redis、MySQL、RabbitMQ 等。
  • 灵活的数据查询和展现方式。
  • 方便的告警功能。
  • 模块化的设计,易于扩展和集成。

Spring Boot 是什么?

Spring Boot 是一个快速构建应用程序的框架,它基于 Spring 框架,简化了 Spring 应用的搭建和开发。Spring Boot 提供了自动化的配置和功能,减少了开发者在配置上花费的时间和精力,使得开发人员可以专注于业务逻辑的实现。

Spring Boot 具有以下特点:

  • 快速构建应用。
  • 提供了自动化配置,最大限度减少了配置的工作量。
  • 开发者友好,提供了灵活的扩展和集成方式。

搭建Spring Boot应用

  首先,我们先创建个基础的Spring Boot项目,如果还不会点这里,此处就不详细赘述啦。

Spring Boot 集成 Prometheus

导入 Prometheus 相关依赖

在 Spring Boot 中使用 Prometheus,需要导入以下两个依赖:

<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_spring_boot</artifactId>
    <version>0.5.0</version>
</dependency>
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_pushgateway</artifactId>
    <version>0.5.0</version>
</dependency>

  simpleclient_spring_boot 是 Prometheus 提供的 Spring Boot 集成包,用于集成 Spring Boot 应用。simpleclient_pushgateway 是用于将采集到的数据推送到 Pushgateway。

配置 Prometheus

在 application.properties 中添加 Prometheus 的配置:

# 启用 Prometheus 进行监控
management.endpoint.metrics.enabled=true
# 设置采集间隔时间,单位为秒,这里设置为 10 秒
management.metrics.export.prometheus.step=10s

这里设置了采集数据的间隔时间为 10 秒。

定义 Controller

在 Controller 中添加用于测试的接口,用于生成一些测试数据:

@RestController
public class TestController {

    private static final Random random = new Random();

    @GetMapping("/test")
    public String test() {
        // 模拟一些业务逻辑,比如查询数据库、计算等。
        try {
            Thread.sleep(random.nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 返回一些测试数据
        return "Hello World!";
    }

}

监控应用

  启动 Spring Boot 应用后,访问 http://localhost:8080/actuator/prometheus 即可查看采集到的数据。

例如,可以查看应用的请求数、请求处理时间、内存使用情况等。

应用场景案例

监控数据库连接池

  数据库连接池是应用中非常重要的资源,过多的连接池占用会导致应用的性能下降,因此需要对其进行监控。在 Spring Boot 应用中可以通过以下方式对数据库连接池进行监控:

  1. 定义一个 health indicator,用于检测连接池的健康状况。
@Component
public class DataSourceHealthIndicator implements HealthIndicator {

    @Autowired
    private DataSource dataSource;

    @Override
    public Health health() {
        try (Connection connection = dataSource.getConnection()) {
            // 如果可以获取到连接,则认为连接池正常
            return Health.up().build();
        } catch (Exception e) {
            // 如果出现异常,则表示连接池不正常
            return Health.down().withException(e).build();
        }
    }

}
  1. 配置 Prometheus 进行监控

在 application.properties 中添加以下配置:

# 启用 Prometheus 进行监控
management.endpoint.metrics.enabled=true
# 设置采集间隔时间,单位为秒,这里设置为 10 秒
management.metrics.export.prometheus.step=10s

监控应用日志

  应用的日志是了解应用运行情况的重要依据,现在有一些日志组件可以与 Prometheus 进行集成,例如 logback-prometheus-appender,其可以将日志输出到 Prometheus 的指标中,方便进行监控。

  在 Spring Boot 应用中可以使用以下方式与 logback-prometheus-appender 集成:

  1. 导入 logback-prometheus-appender 依赖:
<dependency>
    <groupId>io.github.microutils</groupId>
    <artifactId>logback-prometheus-appender</artifactId>
    <version>1.1.0</version>
</dependency>
  1. 在 logback.xml 中添加 appender 和 logger:
<appender name="PROMETHEUS" class="io.github.microutils.vertx.prometheus.LogbackPrometheusAppender">
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n%rEx</pattern>
    </encoder>
</appender>

<logger name="io.github.microutils.vertx.prometheus" level="INFO">
    <appender-ref ref="PROMETHEUS"/>
</logger>

  这里定义了一个名为 PROMETHEUS 的 appender,并配置了 encoder 和 logger,将日志输出到 Prometheus 的指标中。

实战教学

项目结构

  本例中,我们将构建一个简单的 Spring Boot 项目,用于演示如何集成 Prometheus 进行应用监控。项目结构如下:

├── pom.xml
└── src
    └── main
        ├── java
        │   └── io
        │       └── github
        │           └── example
        │               ├── ExampleApplication.java
        │               └── TestController.java
        └── resources
            └── application.properties
  • ExampleApplication:Spring Boot 应用的启动类。
  • TestController:用于生成一些测试数据的 Controller。
  • application.properties:用于配置 Prometheus 和 Spring Boot 应用的属性。

导入依赖

我们需要在 pom.xml 中添加以下依赖:

<dependencies>
    <!-- Spring Boot Web Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.5.6</version>
    </dependency>
    <!-- Prometheus Simple Client for Spring Boot -->
    <dependency>
        <groupId>io.prometheus</groupId>
        <artifactId>simpleclient_spring_boot</artifactId>
        <version>0.10.0</version>
    </dependency>
</dependencies>

  这里我们引入了 Spring Boot Web Starter 和 Prometheus Simple Client for Spring Boot 两个依赖。

配置 Prometheus

在 application.properties 中添加以下内容:

# Prometheus 监控端口
management.server.port=8081
# Prometheus 监控路径
management.endpoints.web.base-path=/actuator/prometheus
# 开启 Micrometer 的 Prometheus 支持
management.metrics.export.prometheus.enabled=true

  这里,我们将 management.server.port 设置为 8081,代表 Prometheus 监控的端口号。management.endpoints.web.base-path 是管理端点的基础路径,用于提供 Prometheus 监控 API。最后,我们开启了 Micrometer 的 Prometheus 支持,这是实现 Spring Boot 应用监控的必要配置。

编写代码

ExampleApplication.java 中添加以下代码:

@SpringBootApplication
public class ExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    @Bean
    public CollectorRegistry collectorRegistry() {
        return CollectorRegistry.defaultRegistry;
    }
}

  这里,我们启用了 Spring Boot 应用,并创建了一个 CollectorRegistry bean。这个 bean 将与 Prometheus 一起使用,以暴露应用程序的度量指标。

接下来,在 TestController.java 中添加以下代码:

@RestController
public class TestController {
    private final Random random = new Random();

    @Autowired
    private CollectorRegistry collectorRegistry;

    @RequestMapping("/test")
    public String test() throws InterruptedException {
        // 模拟请求处理
        Thread.sleep(random.nextInt(500));
        // 增加指标值
        Counter.builder("example_requests_total").register(collectorRegistry).inc();
        return "Test completed";
    }
}

  这里,我们创建了一个 REST 控制器,包含 /test 端点。在这个端点中,我们模拟了请求处理,并增加了 example_requests_total 计数器的值。

运行和测试

现在,我们可以运行应用程序并进行测试了。

首先,启动应用程序:

mvn spring-boot:run

  然后在浏览器中访问 http://localhost:8080/test 。每次访问 /test 端点时,计数器 example_requests_total 将增加一个值。

  接下来,我们使用 Prometheus 来收集应用程序度量指标。在 Prometheus 的配置文件中,添加以下内容:

scrape_configs:
  - job_name: 'example-app'
    metrics_path: '/actuator/prometheus'
    static_configs:
      - targets: ['localhost:8081']

  最后,访问 http://localhost:9090/graph ,在 Query 输入框中输入 example_requests_total,即可看到计数器的值。

小结

  本文介绍了如何在 Spring Boot 应用中集成 Prometheus 进行应用监控,重点讲解了 Prometheus 的概述、Spring Boot 集成 Prometheus 的教学、应用场景案例、实战教学和测试用例。在实践中,我们可以使用 Prometheus 监控数据库连接池、应用日志、文件上传、定时任务等多种场景,通过灵活配置和扩展,帮助我们更好地了解应用的性能和状态。

总结

  Prometheus 是一款开源的系统监控和警报工具包,其具有可扩展性、灵活的数据查询和展现方式、方便的告警功能和模块化的设计等优点。Spring Boot 是一款快速构建应用程序的框架,其提供了自动化的配置和功能,减少了开发者在配置上花费的时间和精力。

  在 Spring Boot 应用中集成 Prometheus,需要导入 Prometheus 相关依赖,配置 Prometheus 和定义 Controller,以便实现数据采集和监控。同时,我们可以根据具体的应用场景,使用不同的方法和工具,对应用的性能和状态进行监控和调优。

  通过本文的介绍和实践,相信大家已经掌握了如何在 Spring Boot 应用中集成 Prometheus 进行应用监控的方法和技巧。希望大家能够灵活运用这些知识,提升应用的性能和稳定性,为业务发展提供有力的保障。

… …

  ok,以上就是我这期的全部内容啦,如果还想学习更多,你可以看看如下的往期热文推荐哦,每天积累一个奇淫小知识,日积月累下去,你一定能成为令人敬仰的大佬。

「赠人玫瑰,手留余香」,咱们下期拜拜~~

🌊热文推荐

滴~如下推荐【Spring Boot 进阶篇】的学习大纲,请小伙伴们注意查收。

Spring Boot进阶(01):Spring Boot 集成 Redis,实现缓存自由

Spring Boot进阶(02):使用Validation进行参数校验

Spring Boot进阶(03):如何使用MyBatis-Plus实现字段的自动填充

Spring Boot进阶(04):如何使用MyBatis-Plus快速实现自定义sql分页

Spring Boot进阶(05):Spring Boot 整合RabbitMq,实现消息队列服务

Spring Boot进阶(06):Windows10系统搭建 RabbitMq Server 服务端

Spring Boot进阶(07):集成EasyPoi,实现Excel/Word的导入导出

Spring Boot进阶(08):集成EasyPoi,实现Excel/Word携带图片导出

Spring Boot进阶(09):集成EasyPoi,实现Excel文件多sheet导入导出

Spring Boot进阶(10):集成EasyPoi,实现Excel模板导出成PDF文件

Spring Boot进阶(11):Spring Boot 如何实现纯文本转成.csv格式文件?

Spring Boot进阶(12):Spring Boot 如何获取Excel sheet页的数量?

Spring Boot进阶(13):Spring Boot 如何获取@ApiModelProperty(value = “序列号“, name = “uuid“)中的value值name值?

Spring Boot进阶(14):Spring Boot 如何手动连接库并获取指定表结构?一文教会你

Spring Boot进阶(15):根据数据库连接信息指定分页查询表结构信息

Spring Boot进阶(16):Spring Boot 如何通过Redis实现手机号验证码功能?

Spring Boot进阶(17):Spring Boot如何在swagger2中配置header请求头等参数信息

Spring Boot进阶(18):SpringBoot如何使用@Scheduled创建定时任务?

Spring Boot进阶(19):Spring Boot 整合ElasticSearch

Spring Boot进阶(20):配置Jetty容器

Spring Boot进阶(21):配置Undertow容器

Spring Boot进阶(22):Tomcat与Undertow容器性能对比分析

Spring Boot进阶(23):实现文件上传

Spring Boot进阶(24):如何快速实现多文件上传?

Spring Boot进阶(25):文件上传的单元测试怎么写?

Spring Boot进阶(26):Mybatis 中 resultType、resultMap详解及实战教学

Spring Boot进阶(27):Spring Boot 整合 kafka(环境搭建+演示)

Spring Boot进阶(28):Jar包Linux后台启动部署及滚动日志查看,日志输出至实体文件保存

Spring Boot进阶(29):如何正确使用@PathVariable,@RequestParam、@RequestBody等注解?不会我教你,结合Postman演示

Spring Boot进阶(30):@RestController和@Controller 注解使用区别,实战演示

… …

  若想系统完整的从0到1的学习,可以参考这篇专栏总结《2023最新首发,全网最全 Spring Boot 学习宝典(附思维导图)》,本专栏致力打造最硬核 Spring Boot 进阶系列学习内容,🚀均为全网独家首发,打造精品专栏,专栏持续更新中。欢迎大家订阅持续学习。

  如果想快速定位学习,可以看这篇【教程导航帖】导航目录,你想学习的都被收集在内,快速投入学习!!两不误。

  在入门及进阶之途,我必助你一臂之力,系统性学习,从入门到精通,带你不走弯路,直奔终点;投资自己,永远性价比最高,都这么说了,你还不赶紧来学??

  本文涉及所有源代码,均已上传至GitHub开源,供同学们一对一参考 GitHub传送门,同时,原创开源不易,欢迎给个star🌟,想体验下被🌟的感jio,非常感谢❗

📣文末

我是bug菌,CSDN | 阿里云 | 华为云 | 51CTO 等社区博客专家,历届博客之星Top30,掘金年度人气作者Top40,51CTO年度博主Top12,掘金 | InfoQ | 51CTO等社区优质创作者,全网粉丝合计15w+ ;硬核微信公众号「猿圈奇妙屋」,欢迎你的加入!免费白嫖最新BAT互联网公司面试题、4000G pdf电子书籍、简历模板等海量资料。


http://www.niftyadmin.cn/n/5130968.html

相关文章

猴子吃桃问题--C语言

问题描述&#xff1a; 猴子第1天摘下若干个桃子&#xff0c;当即吃了一半&#xff0c;还不过瘾&#xff0c;又多吃了一个。第2天早 上又将剩下的桃子吃掉一半&#xff0c;又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天 早上想再吃时&#xff0c;就只剩一…

刷爆指针笔试题

第一题 int main() { int a[5] { 1, 2, 3, 4, 5 }; int *ptr (int *)(&a 1); printf( "%d,%d", *(a 1), *(ptr - 1)); return 0; } //程序的结果是什么&#xff1f; 先自己思考一下&#xff0c;然后再看解析哦 【解析】 &a表示整个数组的地…

JavaScript_Pig Game切换当前玩家

const current0El document.getElementById(current--0); const current1El document.getElementById(current--1); if (dice ! 1) {currentScore dice;current0El.textContent currentScore;} else {} });这是我们上个文章写的代码&#xff0c;这个代码明显是有问题的&…

NNDL:作业五

习题4-1 对于一个神经元,并使用梯度下降优化参数w时,如果输入x恒大于0,其收敛速度会比零均值化的输入更慢. 证明&#xff1a; 激活函数以sigmoid为例。 神经元&#xff1a;有两层&#xff0c;线性层和激活层&#xff1a;yw*xb,然后y‘sigmoid(y)&#xff0c;也就是。 梯度…

2023年第四届MathorCup高校数学建模挑战赛——大数据竞赛A题

赛道 A&#xff1a;基于计算机视觉的坑洼道路检测和识别 坑洼道路检测和识别是一种计算机视觉任务&#xff0c;旨在通过数字图像(通常是地表坑洼图像) 识别出存在坑洼的道路。这对于地质勘探、航天科学和自然灾害等领域的研究和应用具有重要意义。例如&#xff0c;它可以帮助在…

从lc560“和为 K 的子数组“带你认识“前缀和+哈希表“的解题思路

1 前缀和哈希表解题的几道题目&#xff1a;建议集中练习 560. 和为 K 的子数组&#xff1a;https://leetcode.cn/problems/subarray-sum-equals-k/ 1248. 统计「优美子数组」: https://leetcode.cn/problems/count-number-of-nice-subarrays/ 1249. 和可被 K 整除的子数组(利用…

【每日一题】合并两个有序数组

链接奉上&#xff1a;合并两个有序数组 目录 直接合并后排序&#xff1a;思路&#xff1a;代码实现&#xff1a; 双指针思路&#xff1a;代码实现&#xff1a; 直接合并后排序&#xff1a; 思路&#xff1a; 将nums2直接合并到nums1后边&#xff0c;并进行排序 代码实现&…

“第五十三天”

今天没有做什么&#xff0c;不过这个在打印&#xff0c;的时候一直卡着&#xff0c;我一直在想把逗号打印在后面&#xff0c;所以一直想办法确定最后一个是哪一位&#xff0c;这里居然没有绕过来其实可以看做是前面&#xff0c;这样第一个不打印逗号&#xff0c;后面打印就可以…