当前位置: 首页 > article >正文

SpringBoot 项目集成 Prometheus 和 Grafana

下面是一个完整的 Spring Boot 项目示例,集成 Prometheus 和 Grafana 进行性能监控,包括:

  • Prometheus 作为监控数据收集工具
  • Micrometer 作为指标采集库
  • Grafana 作为可视化展示工具

步骤概览

  1. 引入依赖:在 pom.xml 中添加 Prometheus 和 Actuator 相关依赖。
  2. 配置 Spring Boot:启用 Actuator 并暴露 Prometheus 端点。
  3. 编写示例代码:使用 Micrometer 记录应用性能数据。
  4. 配置 Prometheus:拉取 Spring Boot 端点的数据。
  5. 配置 Grafana:可视化 Prometheus 数据。

1. 添加 Maven 依赖

pom.xml 文件中加入:

<dependencies>
    <!-- Spring Boot Actuator 监控 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <!-- Micrometer Prometheus 监控支持 -->
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
    </dependency>
</dependencies>

2. 配置 application.yml

server:
  port: 8080

management:
  endpoints:
    web:
      exposure:
        include: "prometheus, health, info, metrics"
  metrics:
    export:
      prometheus:
        enabled: true

此配置:

  • 允许 Actuator 通过 http://localhost:8080/actuator/prometheus 公开 Prometheus 监控数据。
  • 允许 /actuator/health/actuator/info 等端点。

3. 编写 Spring Boot 监控代码

创建 MonitorController.java,提供测试接口并记录自定义监控指标:

package com.example.monitoring.controller;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.Random;

@RestController
public class MonitorController {
    private final Counter requestCounter;
    private final Timer responseTimer;
    private final Random random = new Random();

    public MonitorController(MeterRegistry registry) {
        this.requestCounter = Counter.builder("api_requests_total")
                .description("Total API Requests")
                .register(registry);
        
        this.responseTimer = Timer.builder("api_response_time")
                .description("API Response Time")
                .register(registry);
    }

    @GetMapping("/hello")
    public String hello(@RequestParam(defaultValue = "World") String name) {
        requestCounter.increment(); // 记录请求数
        
        return responseTimer.record(() -> {  // 记录执行时间
            try {
                Thread.sleep(random.nextInt(500)); // 模拟延迟
            } catch (InterruptedException ignored) {}
            return "Hello, " + name;
        });
    }
}
  • api_requests_total:记录 /hello 接口的总访问量。
  • api_response_time:记录 /hello 的执行时间。

4. 启动 Prometheus

配置 prometheus.yml

prometheus.yml 添加:

global:
  scrape_interval: 5s # 每 5 秒抓取数据

scrape_configs:
  - job_name: 'spring-boot-app'
    metrics_path: '/actuator/prometheus'
    static_configs:
      - targets: ['host.docker.internal:8080']  # 或者改成 'localhost:8080' 取决于你的运行环境

然后运行 Prometheus:

./prometheus --config.file=prometheus.yml

访问 http://localhost:9090,进入 Prometheus 界面,查询 api_requests_total 指标。

5. 启动 Grafana

配置数据源

  1. 访问 http://localhost:3000/(默认账号 admin/admin)。
  2. 添加数据源,选择 Prometheus
  3. 设置 http://localhost:9090 作为数据源地址。
  4. 保存后,在 Explore 面板查询 api_requests_totalapi_response_time

总结

  1. Spring Boot 通过 Actuator 和 Micrometer 采集监控数据。
  2. Prometheus/actuator/prometheus 端点拉取数据。
  3. Grafana 通过 Prometheus 进行数据可视化。

这样,你就成功在 Spring Boot 项目中集成了 Prometheus 和 Grafana 进行性能监控! 🚀


http://www.kler.cn/a/567138.html

相关文章:

  • JAVA版本GDAL安装使用教程(详细步骤)
  • Lucene硬核解析专题系列(三):查询解析与执行
  • ​CNN神经网络概述
  • Docker项目部署-部署Java应用
  • 半音密码:解码音乐的最小量子单位
  • Vue.js 学习笔记
  • 近似最近邻(ANN)算法库实战
  • 5-1JVM内存区域
  • 高频面试题(含笔试高频算法整理)基本总结回顾48
  • C#上位机--三元运算符
  • 为AI聊天工具添加一个知识系统 之127 详细设计之68 编程 核心技术:Cognitive Protocol Language 之1
  • 【Leetcode 每日一题】131. 分割回文串
  • 1.7 Kaggle大白话:Eedi竞赛Transformer框架解决方案07-调用AI模型输出结果
  • 中科大计算机网络原理 1.5 Internt结构和ISP
  • 【Linux高级IO】Linux多路转接:深入探索poll与epoll的奥秘
  • 自学微信小程序的第六天
  • 深入浅出数据结构(图)
  • 钩子项目 -- 实战案例品购物车
  • 数据库基础三(MySQL数据库操作)
  • leetcode35.搜索插入位置