一、 Spring Boot Actuator 概述
Spring Boot Actuator是Spring Boot 提供的生產級監控與管理工具集,用于實時監控和運維管理應用。Actuator 通過HTTP 端點(或 JMX 端點)暴露應用的健康狀態、性能指標、日志信息、環境配置等關鍵數據,使開發者和運維人員能夠高效地監測應用狀態、優化性能、排查問題,尤其適用于生產環境。
核心功能:
1.健康檢查(Health Checks)
? 提供應用的運行健康狀態,可監控數據庫、緩存、消息隊列等依賴服務,通常用于服務可用性探測(如 Kubernetes 健康檢查)。
? 通過/actuator/health端點訪問,返回UP(正常)或 DOWN(異常),支持自定義健康檢查。
2.度量指標(Metrics)
? 提供應用的性能指標,包括JVM 內存使用、GC 狀態、線程數、數據庫連接池狀態等。
? 通過/actuator/metrics端點訪問,可與Prometheus、Grafana、Micrometer結合,實現完整的應用監控方案。
3.日志管理(Logging)
? 通過/actuator/loggers端點,支持實時調整日志級別,避免生產環境修改配置后必須重啟應用的麻煩。
? /actuator/logfile端點可直接查看應用日志文件(需額外配置logging.file.name或logging.file.path)。
4.環境信息(Environment Info)
? 通過/actuator/env端點,查看應用當前的環境變量、配置屬性、系統參數等,方便排查配置問題。
? /actuator/configprops端點可查看所有@ConfigurationProperties 配置項,直觀了解 Spring Boot 自動配置細節。
二、 集成 Spring Boot Actuator
Spring Boot Actuator 提供了一套開箱即用的監控和管理工具,集成非常簡單,只需添加依賴、啟用端點并配置訪問權限即可。
步驟1:Maven 依賴配置
在pom.xml文件中引入 Spring Boot Actuator 依賴。
<dependencies><!-- Spring Boot Actuator --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
</dependencies>
添加依賴后,Actuator 的部分端點會默認啟用,無需額外代碼即可使用。
步驟2: 啟用 Actuator 端點
Actuator 端點分為默認啟用端點和需手動啟用端點。
默認啟用的端點:
? /actuator/health:應用健康狀況
? /actuator/info:應用基本信息
非默認啟用端點:
以下端點默認可用但未暴露,需要手動啟用:
? /actuator/metrics:應用性能指標(JVM 內存、GC、請求數等)
? /actuator/env:應用環境變量、系統屬性
? /actuator/logfile:訪問日志文件(需額外配置日志路徑)
? /actuator/heapdump:下載 JVM 堆轉儲文件
? /actuator/threads:查看線程信息
? /actuator/configprops:查看@ConfigurationProperties配置項
? /actuator/caches:查看緩存狀態
? /actuator/beans:列出 Spring Beans
? /actuator/auditevents:Spring Security 審計事件
啟用非默認端點
在application.properties或application.yml中配置。
在 application.properties 中:
# 啟用指定端點
management.endpoints.web.exposure.include=metrics,logfile
# 啟用所有端點
management.endpoints.web.exposure.include=*
在 application.yml 中:management:endpoints:web:exposure:include: env,metrics
配置日志路徑(適用于 /logfile 端點)
/logfile端點顯示暴露后,還需在application.properties配置日志文件路徑:
management.endpoint.logfile.external-file=/var/log/myapp.log
步驟3:訪問Actuator端點
1.訪問健康檢查端點(Health Check):
http://localhost:8080/actuator/health
響應示例:
{"status": "UP"
}
? UP表示應用正常運行。
? DOWN表示應用不健康。
? OUT_OF_SERVICE表示應用正在停止。
2.訪問度量指標端點(Metrics):
http://localhost:8080/actuator/metrics
響應示例:
{"names": ["jvm.memory.used","jvm.gc.pause","http.server.requests"]
}
訪問特定指標,查看具體數值:
http://localhost:8080/actuator/metrics/jvm.memory.used
返回的內容:
{"name": "jvm.memory.used","measurements": [{"statistic": "VALUE","value": 12345678}],"availableTags": [{"tag": "area","values": ["heap", "non-heap"]}]
}
3.訪問信息端點(Info):
http://localhost:8080/actuator/info
響應示例:
{"app": {"name": "MyApp","version": "1.0.0"}
}
三、 自定義 Actuator 端點
Spring Boot Actuator 提供了豐富的內置端點,但在某些情況下,需要自定義端點以滿足特定的監控需求。Actuator 支持兩種方式創建自定義端點:
? 實現 Endpoint 接口
? 繼承 AbstractEndpoint(已在較早版本使用,現推薦 @Endpoint 注解方式)
步驟1:創建自定義端點類
簡單示例:
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;@Component
@Endpoint(id = "custom")
public class CustomEndpoint {@ReadOperationpublic String customEndpoint() {return "這是自定義的 Actuator 端點";}
}
代碼解析:
? @Endpoint(id = “custom”):定義自定義端點/actuator/custom。
? @ReadOperation:指定該方法用于 GET 請求,返回端點的數據。
步驟2:配置暴露自定義端點
默認情況下,Spring Boot 僅暴露health和info端點。要使自定義端點可訪問,需要在application.properties或application.yml配置:
management.endpoints.web.exposure.include=custom
或在application.yml中:
management:endpoints:web:exposure:include: custom
步驟3:訪問自定義端點
應用啟動后,可通過以下 URL 訪問:
http://localhost:8080/actuator/custom
響應:
"這是自定義的 Actuator 端點"
四、端點擴展
在 Spring Boot Actuator 中,除了自定義端點,還可以對已有端點進行擴展,以增強其功能。在不重新創建端點的情況下,滿足特定業務需求。
1. 擴展健康檢查(HealthIndicator)
/actuator/health端點默認檢查應用的基本健康狀態。我們可以通過實現HealthIndicator接口,擴展健康檢查邏輯,例如,檢查應用的數據庫連接、第三方服務的狀態等。
代碼示例:檢查數據庫是否正常
@Component
public class DatabaseHealthIndicator implements HealthIndicator {@Overridepublic Health health() {// 數據庫連接檢查boolean isDatabaseHealthy = checkDatabase();// 根據數據庫健康狀態返回健康狀態if (isDatabaseHealthy) {return Health.up().withDetail("Database", "OK").build();} else {return Health.down().withDetail("Database", "Not reachable").build();}}// 模擬數據庫連接檢查的方法private boolean checkDatabase() {// 這里可以寫實際的數據庫連接檢查邏輯// 如,通過 JDBC 或連接池檢查數據庫連接return true; // 假設數據庫連接正常}
}
代碼解析:
? @Component: 標記DatabaseHealthIndicator為 Spring Bean,確保被 Spring 掃描并注冊。
? HealthIndicator接口:自定義健康檢查邏輯的基類。
? health():檢查數據庫連接。正常返回UP,否則返回DOWN。
健康檢查結果:
訪問/actuator/health,如果數據庫正常:
{"status": "UP","details": {"Database": "OK"}
}
如果數據庫不可用:
{"status": "DOWN","details": {"Database": "Not reachable"}
}
2. 擴展日志管理(動態修改日志級別)
/actuator/logfile端點提供了日志內容的查看功能。Spring Boot 允許通過logback-spring.xml配置文件動態控制日志級別。
代碼示例:
<configuration><!-- 控制根日志級別為INFO --><root level="INFO"><appender-ref ref="CONSOLE"/></root><!-- 定義日志級別為DEBUG --><logger name="com.example" level="DEBUG"/><!-- 控制日志輸出格式 --><appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss} - %msg%n</pattern></encoder></appender>
</configuration>
代碼解析:
? <root level="INFO">: 設置根日志級別為INFO,即顯示INFO及更高級別的日志(如WARN,ERROR)。? <logger name="com.example" level="DEBUG"/>: 為特定包(com.example)設置DEBUG級別日志,使得它顯示更多細節。? <appender>: 定義日志輸出方式(例如,輸出到控制臺)。
動態修改日志級別:
通過/actuator/loggers端點動態修改日志級別,例如:
1.查看當前日志級別:
GET /actuator/loggers/com.example
2.動態修改日志級別:
POST /actuator/loggers/com.example
Content-Type: application/json
{"configuredLevel": "DEBUG"
}
修改后,日志系統會立即生效,而無需重啟應用。
3. 擴展度量指標(Metrics)
使用MeterRegistry注冊自定義指標,例如,添加自定義計數器:
@Component
public class CustomMetrics {private final MeterRegistry meterRegistry;public CustomMetrics(MeterRegistry meterRegistry) {this.meterRegistry = meterRegistry;}@PostConstructpublic void init() {Counter counter = meterRegistry.counter("custom.counter");counter.increment(); // 每次調用時遞增}
}
訪問/actuator/metrics可查看custom.counter指標。
4. 其他常見端點擴展
除了健康檢查、度量指標和日志管理,Spring Boot Actuator 還支持其他端點的擴展,以提供更豐富的監控和管理能力,例如:
? 環境配置(Environment)
通過擴展/actuator/env端點,可以暴露更多的環境變量或系統屬性,以便在運行時查看和調試應用配置。
? 審計事件(Audit Events)
通過擴展/actuator/auditevents端點,可以自定義審計事件的記錄和查詢,例如用戶登錄、權限變更等關鍵事件的追蹤。
? 配置屬性(Config Props)
通過擴展/actuator/configprops端點,可以暴露更多的應用配置屬性,以便分析 Spring Boot 自動配置的內容,幫助開發者更好地理解應用的運行狀態。
總結
? 自定義端點:使用@Endpoint創建新端點,如/actuator/custom。
? 端點擴展:
? 健康檢查:使用HealthIndicator擴展/actuator/health。
? 日志管理:通過/actuator/loggers端點動態調整日志級別。
? 度量指標:使用MeterRegistry添加自定義指標。
五、端點安全管理
為了確保 Spring Boot Actuator 端點的訪問安全,推薦使用 Spring Security 配置權限控制。以防止未授權的訪問,保護敏感數據。以下是配置端點安全的基本步驟:
步驟1:引入 Spring Security 依賴
在pom.xml文件中添加 Spring Security 依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
步驟2:配置安全策略
使用@EnableWebSecurity注解和WebSecurityConfigurerAdapter配置 Actuator 端點的訪問權限,例如:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/actuator/**").hasRole("ADMIN") // 僅允許 ADMIN 角色訪問.anyRequest().authenticated() // 其他請求需認證.and().httpBasic(); // 啟用基本認證}
}
步驟3:配置用戶名和密碼
Spring Boot 默認會生成隨機用戶名和密碼。要使用自定義憑據,可在application.properties或application.yml配置:
spring.security.user.name=admin
spring.security.user.password=secret
步驟4:精細化保護 Actuator 端點
配置哪些端點對外開放。例如:
management.endpoints.web.exposure.include=health,info // 開放 health 和 info 端點
management.endpoints.web.exposure.exclude=metrics,env // 排除 metrics 和 env 端點
端點安全的最佳實踐:
? 最小化暴露端點:僅開放必要的端點,減少安全風險。
? 使用角色權限控制:確保敏感端點只能由特定角色訪問。
? 啟用 HTTPS:在生產環境中,強制使用 HTTPS 保護數據傳輸安全。
? 結合 API 網關或身份認證服務:如 Keycloak、OAuth2 進行細粒度訪問控制。
通過以上安全策略,可以有效保護 Actuator 端點,確保監控數據的安全性。
六、監控與管理常用示例
Spring Boot Actuator 提供了豐富的端點,可用于監控和管理應用。下面介紹幾個常見的使用場景,幫助你在生產環境中高效監控應用狀態。
1. 健康檢查端點的應用
健康檢查是 Actuator 最常用的功能之一,常用于:
? 應用存活檢測:判斷服務是否正常運行,可用于負載均衡器的健康檢查。
? 外部依賴檢查:檢測數據庫、緩存、第三方 API 是否可用,保障系統穩定性。
最佳實踐
? 自定義健康檢查
如,檢查數據庫狀態、MQ 消息隊列是否正常。
? 與負載均衡器集成
負載均衡器(如 Nginx、Kubernetes)可通過/actuator/health判斷服務健康狀態,自動進行流量分配或故障轉移。
2.自定義度量指標的應用
Actuator 端點/actuator/metrics提供 JVM 運行時、線程池、HTTP 請求等性能指標。可以使用MeterRegistry添加自定義度量指標。
最佳實踐:
? 添加 API 請求計數、耗時統計:監控接口調用頻率和性能瓶頸。
? 集成 Prometheus/Grafana:通過可視化工具實時查看度量數據。
3.日志管理擴展
日志是調試和運維的重要工具,Actuator 允許動態修改日志級別,無需重啟應用。
最佳實踐:
? 生產環境下,日志級別默認設置為 WARN 或 ERROR,僅記錄關鍵信息。
? 調試時,可動態調整為 DEBUG 級別,快速排查問題。
? 結合 ELK(Elasticsearch + Logstash + Kibana)等日志分析工具,提高故障診斷效率。
七、總結
1. 核心要點
? 集成 Spring Boot Actuator
提供開箱即用的監控和管理功能,幫助監控應用健康和性能。
? 自定義和擴展端點
可根據業務需求定制健康檢查、度量指標等,擴展 Actuator 的功能。
? 端點安全管理
使用 Spring Security 配置權限控制,確保端點訪問的安全性