用 Prometheus 監控 Spring Boot 應用程式

透過 Actuator 與 Micrometer 設定受控的 Prometheus 抓取端點,觀察訂單受理件數、處理中請求數和耗時 P95。

最佳實務
Prometheus 監控與儀表板示意圖

訂單 API 開始拒絕更多請求,HTTP 請求數也跟著上升,但其中同時計入受理和拒絕。把 Spring Boot 的 HTTP 指標與只計算受理訂單的業務計數器放在一起,才看得出哪個環節有變化。處理時間的分佈則交給直方圖。

設定抓取端點的存取範圍

範例採用 Java 21、Spring Boot 3.5.16,以及由 Spring Boot 管理版本的 Micrometer 1.15.12。將以下 Maven 專案定義儲存為 pom.xml。

<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.16</version>
        <relativePath/>
    </parent>
    <groupId>example</groupId>
    <artifactId>checkout-metrics</artifactId>
    <version>1.0.0</version>
    <properties><java.version>21</java.version></properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

把下列設定儲存為 src/main/resources/application.properties。兩個監聽位址均使用 loopback,管理連接埠透過 HTTP 提供健康檢查和 Prometheus 端點。

server.address=127.0.0.1
server.port=8080
management.server.address=127.0.0.1
management.server.port=9091
management.endpoints.web.exposure.include=health,prometheus

加入下方應用程式碼後執行 mvn spring-boot:run,從同一網路命名空間開啟 http://127.0.0.1:9091/actuator/prometheus。Actuator 透過 Prometheus 註冊表提供抓取格式,公開清單決定哪些端點可經由 HTTP 存取。獨立管理連接埠本身不會提供身分驗證。若要讓遠端收集器抓取,應提供它可到達的管理位址,並限制存取來源。如果自訂 Spring Security 過濾鏈,也要核對 Actuator 的存取規則。Spring Boot Actuator 端點(英文) · 管理連接埠設定(英文)

先檢查 JVM 與 HTTP 時間序列

查看 jvm_memory_used_bytes 的各個記憶體集區,以及 jvm_threads_live_threads 的存活執行緒數。視 JVM 和 GC 事件而定,也可能出現 jvm_gc_pause_seconds_count 與 _sum。堆積用量或執行緒數上升時,可以先比較負載相近的時段,再檢查物件保留情況或執行緒堆疊,判斷是否有洩漏。Spring Boot 3.5 的嵌入式 Tomcat 要先用 server.tomcat.mbeanregistry.enabled=true 啟用 MBean 註冊表,才會提供相關的執行緒集區指標。

Spring MVC 以 http.server.requests 記錄 HTTP 請求。呼叫路由之後,可在 Prometheus 輸出裡看到 http_server_requests_seconds_count、_sum 等時間序列。用匹配後的 uri 路由範本和狀態標籤,可分辨 /checkout/{orderId} 的受理與拒絕。預設 Timer 不一定輸出延遲桶。製作百分位數面板前,先確認有沒有 _bucket。Spring Boot HTTP 與 JVM 指標(英文)

量測訂單受理量與處理時間

將程式儲存為 src/main/java/example/checkout/CheckoutApplication.java。範例特意拒絕一個訂單 ID,並分開記錄受理件數、處理中的請求數和處理器耗時。

package example.checkout;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
class CheckoutController {
    private final MeterRegistry registry;
    private final AtomicInteger inFlight = new AtomicInteger();
    private final Counter accepted;
    private final Timer duration;

    CheckoutController(MeterRegistry registry) {
        this.registry = registry;
        accepted = registry.counter("checkout.accepted", "channel", "web");
        Gauge.builder("checkout.in.flight", inFlight, AtomicInteger::get)
            .register(registry);
        duration = Timer.builder("checkout.duration")
            .publishPercentileHistogram()
            .serviceLevelObjectives(Duration.ofMillis(250))
            .register(registry);
    }

    @PostMapping("/checkout/{orderId}")
    ResponseEntity<Void> checkout(@PathVariable("orderId") String orderId) {
        Timer.Sample sample = Timer.start(registry);
        inFlight.incrementAndGet();
        try {
            if ("declined".equals(orderId)) {
                return ResponseEntity.unprocessableEntity().build();
            }
            accepted.increment();
            return ResponseEntity.noContent().build();
        } finally {
            inFlight.decrementAndGet();
            sample.stop(duration);
        }
    }
}

在剛啟動的執行個體中,各執行一次 curl -X POST http://127.0.0.1:8080/checkout/42 和 curl -X POST http://127.0.0.1:8080/checkout/declined,再抓取管理端點。

時間序列 應看到的變化 含義
checkout_accepted_total 增加 1 受理一筆訂單
checkout_duration_seconds_count 增加 2 受理與拒絕都計入
checkout_in_flight 兩筆請求完成後回到 0 抓取時點正在處理的請求數

Gauge 預設對觀測對象使用弱參照,因此範例將 AtomicInteger 保存在控制器欄位。短暫的尖峰可能發生在兩次抓取之間。若要看這段期間累計的件數,依問題選用 Counter 或 Timer 的計數。訂單 ID 不宜放進指標標籤。範例只用固定的 channel 值與標準 HTTP 路由範本。Micrometer Gauge(英文)

抓取直方圖,再查詢 P95

如果 Prometheus 與應用程式在同一個網路命名空間,可使用以下工作設定。

scrape_configs:
  - job_name: spring-app
    metrics_path: /actuator/prometheus
    static_configs:
      - targets: ["127.0.0.1:9091"]

自訂 Timer 啟用百分位數直方圖,並把 250 毫秒的目標加入桶邊界。確認抓取結果有 checkout_duration_seconds_bucket。次數和耗時總和可用來算平均值,估算百分位數則需要分佈。先對累計桶套用 rate,保留 le 再彙總。跨執行個體加總時,各端必須使用一致的桶邊界。以下查詢估算處理器耗時的 P95,單位為秒。

histogram_quantile(
  0.95,
  sum by (le) (rate(checkout_duration_seconds_bucket{job="spring-app"}[5m]))
)

既有儀表板若使用 http.server.requests,需要 HTTP 百分位數時,請另外啟用並核對該指標的直方圖。應用程式各自算出的百分位數無法直接合併成全體執行個體的百分位數。Micrometer 直方圖與百分位數(英文) · Prometheus 直方圖查詢(英文)

若要收集至觀測雲,請在 DataKit Prom 收集器(簡體中文) 設定實際可到達的端點。核對抓取原文與收集後的名稱、標籤及單位,再合併觀察受理訂單數、HTTP 狀態分佈和處理耗時 P95。這有助於分辨業務規則拒絕了更多訂單,還是整條請求路徑變慢。RED 與 USE 方法

取得專屬方案

聯絡我們

加入社群

微信扫码
加入官方交流群

立即體驗

在线开通,按量计费,真正的云服务!

立即開始

选择观测云版本

代码托管平台