Spring Boot Actuator自定義指標與監控實踐指南
本篇文章以生產環境實戰經驗為主線,結合某電商系統的業務場景,講解如何在Spring Boot Actuator中添加并暴露自定義指標,并使用Prometheus和Grafana進行完整的監控與告警配置。
一、業務場景描述
在電商系統中,我們希望監控以下關鍵指標:
- 下單接口響應時間(Order API Latency)
- 庫存鎖定成功次數(Inventory Lock Success Count)
- 訂單支付失敗率(Payment Failure Rate)
- 用戶訪問量(Active Users)
傳統的日志埋點無法滿足實時監控需求,通過Spring Boot Actuator與Micrometer,可以快速采集并暴露應用指標。
二、技術選型過程
我們選用了以下技術棧:
- Spring Boot Actuator:提供內置監控端點
- Micrometer:度量指標采集框架,兼容常見監控系統
- Prometheus:指標拉取與存儲
- Grafana:可視化展示與告警規則
該方案能夠無縫集成Spring生態,具備開箱即用和自定義擴展能力。
三、實現方案詳解
3.1 引入依賴
在pom.xml
中添加:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
3.2 配置application.yml
management:endpoints:web:exposure:include: health,info,prometheusmetrics:export:prometheus:enabled: true
3.3 自定義指標實現
創建一個MetricsService
,在業務邏輯中注入MetricsRegistry:
package com.example.monitor;import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.stereotype.Service;@Service
public class MetricsService {private final Counter inventoryLockCounter;private final Timer orderLatencyTimer;public MetricsService(MeterRegistry registry) {this.inventoryLockCounter = Counter.builder("inventory.lock.success.count").description("庫存鎖定成功次數").register(registry);this.orderLatencyTimer = Timer.builder("order.api.latency").description("下單接口響應時間").publishPercentiles(0.5, 0.95).register(registry);}public void recordInventoryLockSuccess() {inventoryLockCounter.increment();}public <T> T recordOrderLatency(Supplier<T> supplier) {return orderLatencyTimer.record(supplier);}
}
在OrderController
中使用:
@RestController
@RequestMapping("/api/orders")
public class OrderController {private final MetricsService metricsService;private final OrderService orderService;public OrderController(MetricsService metricsService, OrderService orderService) {this.metricsService = metricsService;this.orderService = orderService;}@PostMappingpublic ResponseEntity<Order> createOrder(@RequestBody OrderRequest req) {// 記錄訂單處理時間Order order = metricsService.recordOrderLatency(() -> orderService.createOrder(req));// 記錄庫存鎖定成功次數metricsService.recordInventoryLockSuccess();return ResponseEntity.ok(order);}
}
3.4 Prometheus與Grafana集成
- 在Prometheus配置中添加Spring Boot應用地址:
scrape_configs:- job_name: 'spring-boot-app'static_configs:- targets: ['app-host:8080']
- Grafana中導入Dashboard模板(可參考官方Micrometer模板),或自行創建:
- 使用
order_api_latency
查詢響應時間分布 - 使用
inventory_lock_success_count
監控鎖定次數
- 使用
3.5 完整項目結構示例
monitoring-sample/
├─ src/
│ ├─ main/
│ │ ├─ java/com/example/monitor/ # 業務代碼與監控實現
│ │ └─ resources/
│ │ └─ application.yml # Actuator和Prometheus配置
│ └─ test/
└─ pom.xml
四、踩過的坑與解決方案
-
自定義指標未暴露:
- 原因:未在
application.yml
中啟用prometheus
端點 - 解決:
management.endpoints.web.exposure.include: prometheus
- 原因:未在
-
Label標簽過多導致高基數問題:
- 避免使用用戶ID、動態路徑作為標簽
- 建議只使用固定維度,如
region
、status
等
-
Prometheus拉取失敗:
- 檢查網絡與防火墻
- 確認拉取路徑
/actuator/prometheus
正確
-
Grafana圖表無數據:
- 檢查Prometheus中是否已有歷史數據
- 調整Dashboard查詢語句和時間范圍
五、總結與最佳實踐
- 為關鍵業務埋點自定義指標,并使用合理的單位和命名規范
- 限制標簽基數,避免高基數帶來的存儲和查詢壓力
- 合理設置Prometheus抓取頻率和數據保留策略
- 在Grafana中通過告警規則及時通知異常狀態
- 定期評審指標體系,保持指標與業務場景同步
通過以上實踐,可在Spring Boot應用中高效地監控業務性能,實現故障預警與性能優化。