下面是一个完整的 Spring Boot 项目示例,集成 Prometheus 和 Grafana 进行性能监控,包括:
pom.xml
中添加 Prometheus 和 Actuator 相关依赖。在 pom.xml
文件中加入:
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>io.micrometergroupId>
<artifactId>micrometer-registry-prometheusartifactId>
dependency>
dependencies>
application.yml
server:
port: 8080
management:
endpoints:
web:
exposure:
include: "prometheus, health, info, metrics"
metrics:
export:
prometheus:
enabled: true
此配置:
http://localhost:8080/actuator/prometheus
公开 Prometheus 监控数据。/actuator/health
、/actuator/info
等端点。创建 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
的执行时间。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
指标。
http://localhost:3000/
(默认账号 admin/admin
)。Prometheus
。http://localhost:9090
作为数据源地址。Explore
面板查询 api_requests_total
和 api_response_time
。/actuator/prometheus
端点拉取数据。这样,你就成功在 Spring Boot 项目中集成了 Prometheus 和 Grafana 进行性能监控!