Spring Boot Actuator應(yīng)用監(jiān)控與管理的詳細步驟
一、 Spring Boot Actuator 概述
Spring Boot Actuator是Spring Boot 提供的生產(chǎn)級監(jiān)控與管理工具集,用于實時監(jiān)控和運維管理應(yīng)用。Actuator 通過HTTP 端點(或 JMX 端點)暴露應(yīng)用的健康狀態(tài)、性能指標(biāo)、日志信息、環(huán)境配置等關(guān)鍵數(shù)據(jù),使開發(fā)者和運維人員能夠高效地監(jiān)測應(yīng)用狀態(tài)、優(yōu)化性能、排查問題,尤其適用于生產(chǎn)環(huán)境。
核心功能:
1.健康檢查(Health Checks)
• 提供應(yīng)用的運行健康狀態(tài),可監(jiān)控數(shù)據(jù)庫、緩存、消息隊列等依賴服務(wù),通常用于服務(wù)可用性探測(如 Kubernetes 健康檢查)。
• 通過/actuator/health端點訪問,返回UP(正常)或 DOWN(異常),支持自定義健康檢查。
2.度量指標(biāo)(Metrics)
• 提供應(yīng)用的性能指標(biāo),包括JVM 內(nèi)存使用、GC 狀態(tài)、線程數(shù)、數(shù)據(jù)庫連接池狀態(tài)等。
• 通過/actuator/metrics端點訪問,可與Prometheus、Grafana、Micrometer結(jié)合,實現(xiàn)完整的應(yīng)用監(jiān)控方案。
3.日志管理(Logging)
• 通過/actuator/loggers端點,支持實時調(diào)整日志級別,避免生產(chǎn)環(huán)境修改配置后必須重啟應(yīng)用的麻煩。
• /actuator/logfile端點可直接查看應(yīng)用日志文件(需額外配置logging.file.name或logging.file.path)。
4.環(huán)境信息(Environment Info)
• 通過/actuator/env端點,查看應(yīng)用當(dāng)前的環(huán)境變量、配置屬性、系統(tǒng)參數(shù)等,方便排查配置問題。
• /actuator/configprops端點可查看所有@ConfigurationProperties 配置項,直觀了解 Spring Boot 自動配置細節(jié)。
二、 集成 Spring Boot Actuator
Spring Boot Actuator 提供了一套開箱即用的監(jiān)控和管理工具,集成非常簡單,只需添加依賴、啟用端點并配置訪問權(quán)限即可。
步驟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 的部分端點會默認(rèn)啟用,無需額外代碼即可使用。
步驟2: 啟用 Actuator 端點
Actuator 端點分為默認(rèn)啟用端點和需手動啟用端點。
默認(rèn)啟用的端點:
• /actuator/health:應(yīng)用健康狀況
• /actuator/info:應(yīng)用基本信息
非默認(rèn)啟用端點:
以下端點默認(rèn)可用但未暴露,需要手動啟用:
• /actuator/metrics:應(yīng)用性能指標(biāo)(JVM 內(nèi)存、GC、請求數(shù)等)
• /actuator/env:應(yīng)用環(huán)境變量、系統(tǒng)屬性
• /actuator/logfile:訪問日志文件(需額外配置日志路徑)
• /actuator/heapdump:下載 JVM 堆轉(zhuǎn)儲文件
• /actuator/threads:查看線程信息
• /actuator/configprops:查看@ConfigurationProperties配置項
• /actuator/caches:查看緩存狀態(tài)
• /actuator/beans:列出 Spring Beans
• /actuator/auditevents:Spring Security 審計事件
啟用非默認(rèn)端點
在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
響應(yīng)示例:
{
"status": "UP"
}• UP表示應(yīng)用正常運行。
• DOWN表示應(yīng)用不健康。
• OUT_OF_SERVICE表示應(yīng)用正在停止。
2.訪問度量指標(biāo)端點(Metrics):
http://localhost:8080/actuator/metrics
響應(yīng)示例:
{
"names": [
"jvm.memory.used",
"jvm.gc.pause",
"http.server.requests"
]
}訪問特定指標(biāo),查看具體數(shù)值:
http://localhost:8080/actuator/metrics/jvm.memory.used
返回的內(nèi)容:
{
"name": "jvm.memory.used",
"measurements": [
{
"statistic": "VALUE",
"value": 12345678
}
],
"availableTags": [
{
"tag": "area",
"values": ["heap", "non-heap"]
}
]
}3.訪問信息端點(Info):
http://localhost:8080/actuator/info
響應(yīng)示例:
{
"app": {
"name": "MyApp",
"version": "1.0.0"
}
}三、 自定義 Actuator 端點
Spring Boot Actuator 提供了豐富的內(nèi)置端點,但在某些情況下,需要自定義端點以滿足特定的監(jiān)控需求。Actuator 支持兩種方式創(chuàng)建自定義端點:
• 實現(xiàn) Endpoint 接口
• 繼承 AbstractEndpoint(已在較早版本使用,現(xiàn)推薦 @Endpoint 注解方式)
步驟1:創(chuàng)建自定義端點類
簡單示例:
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 {
@ReadOperation
public String customEndpoint() {
return "這是自定義的 Actuator 端點";
}
}代碼解析:
• @Endpoint(id = “custom”):定義自定義端點/actuator/custom。
• @ReadOperation:指定該方法用于 GET 請求,返回端點的數(shù)據(jù)。
步驟2:配置暴露自定義端點
默認(rèn)情況下,Spring Boot 僅暴露health和info端點。要使自定義端點可訪問,需要在application.properties或application.yml配置:
management.endpoints.web.exposure.include=custom
或在application.yml中:
management:
endpoints:
web:
exposure:
include: custom步驟3:訪問自定義端點
應(yīng)用啟動后,可通過以下 URL 訪問:
http://localhost:8080/actuator/custom
響應(yīng):
"這是自定義的 Actuator 端點"
四、端點擴展
在 Spring Boot Actuator 中,除了自定義端點,還可以對已有端點進行擴展,以增強其功能。在不重新創(chuàng)建端點的情況下,滿足特定業(yè)務(wù)需求。
1. 擴展健康檢查(HealthIndicator)
/actuator/health端點默認(rèn)檢查應(yīng)用的基本健康狀態(tài)。我們可以通過實現(xiàn)HealthIndicator接口,擴展健康檢查邏輯,例如,檢查應(yīng)用的數(shù)據(jù)庫連接、第三方服務(wù)的狀態(tài)等。
代碼示例:檢查數(shù)據(jù)庫是否正常
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// 數(shù)據(jù)庫連接檢查
boolean isDatabaseHealthy = checkDatabase();
// 根據(jù)數(shù)據(jù)庫健康狀態(tài)返回健康狀態(tài)
if (isDatabaseHealthy) {
return Health.up().withDetail("Database", "OK").build();
} else {
return Health.down().withDetail("Database", "Not reachable").build();
}
}
// 模擬數(shù)據(jù)庫連接檢查的方法
private boolean checkDatabase() {
// 這里可以寫實際的數(shù)據(jù)庫連接檢查邏輯
// 如,通過 JDBC 或連接池檢查數(shù)據(jù)庫連接
return true; // 假設(shè)數(shù)據(jù)庫連接正常
}
}代碼解析:
• @Component: 標(biāo)記DatabaseHealthIndicator為 Spring Bean,確保被 Spring 掃描并注冊。
• HealthIndicator接口:自定義健康檢查邏輯的基類。
• health():檢查數(shù)據(jù)庫連接。正常返回UP,否則返回DOWN。
健康檢查結(jié)果:
訪問/actuator/health,如果數(shù)據(jù)庫正常:
{
"status": "UP",
"details": {
"Database": "OK"
}
}
如果數(shù)據(jù)庫不可用:
{
"status": "DOWN",
"details": {
"Database": "Not reachable"
}
}
2. 擴展日志管理(動態(tài)修改日志級別)
/actuator/logfile端點提供了日志內(nèi)容的查看功能。Spring Boot 允許通過logback-spring.xml配置文件動態(tài)控制日志級別。
代碼示例:
<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">: 設(shè)置根日志級別為INFO,即顯示INFO及更高級別的日志(如WARN,ERROR)。 ? <logger name="com.example" level="DEBUG"/>: 為特定包(com.example)設(shè)置DEBUG級別日志,使得它顯示更多細節(jié)。 ? <appender>: 定義日志輸出方式(例如,輸出到控制臺)。
動態(tài)修改日志級別:
通過/actuator/loggers端點動態(tài)修改日志級別,例如:
1.查看當(dāng)前日志級別:
GET /actuator/loggers/com.example
2.動態(tài)修改日志級別:
POST /actuator/loggers/com.example
Content-Type: application/json
{
"configuredLevel": "DEBUG"
}
修改后,日志系統(tǒng)會立即生效,而無需重啟應(yīng)用。
3. 擴展度量指標(biāo)(Metrics)
使用MeterRegistry注冊自定義指標(biāo),例如,添加自定義計數(shù)器:
@Component
public class CustomMetrics {
private final MeterRegistry meterRegistry;
public CustomMetrics(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
@PostConstruct
public void init() {
Counter counter = meterRegistry.counter("custom.counter");
counter.increment(); // 每次調(diào)用時遞增
}
}訪問/actuator/metrics可查看custom.counter指標(biāo)。
4. 其他常見端點擴展
除了健康檢查、度量指標(biāo)和日志管理,Spring Boot Actuator 還支持其他端點的擴展,以提供更豐富的監(jiān)控和管理能力,例如:
• 環(huán)境配置(Environment)
通過擴展/actuator/env端點,可以暴露更多的環(huán)境變量或系統(tǒng)屬性,以便在運行時查看和調(diào)試應(yīng)用配置。
• 審計事件(Audit Events)
通過擴展/actuator/auditevents端點,可以自定義審計事件的記錄和查詢,例如用戶登錄、權(quán)限變更等關(guān)鍵事件的追蹤。
• 配置屬性(Config Props)
通過擴展/actuator/configprops端點,可以暴露更多的應(yīng)用配置屬性,以便分析 Spring Boot 自動配置的內(nèi)容,幫助開發(fā)者更好地理解應(yīng)用的運行狀態(tài)。
總結(jié)
• 自定義端點:使用@Endpoint創(chuàng)建新端點,如/actuator/custom。
• 端點擴展:
• 健康檢查:使用HealthIndicator擴展/actuator/health。
• 日志管理:通過/actuator/loggers端點動態(tài)調(diào)整日志級別。
• 度量指標(biāo):使用MeterRegistry添加自定義指標(biāo)。
五、端點安全管理
為了確保 Spring Boot Actuator 端點的訪問安全,推薦使用 Spring Security 配置權(quán)限控制。以防止未授權(quán)的訪問,保護敏感數(shù)據(jù)。以下是配置端點安全的基本步驟:
步驟1:引入 Spring Security 依賴
在pom.xml文件中添加 Spring Security 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>步驟2:配置安全策略
使用@EnableWebSecurity注解和WebSecurityConfigurerAdapter配置 Actuator 端點的訪問權(quán)限,例如:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/actuator/**").hasRole("ADMIN") // 僅允許 ADMIN 角色訪問
.anyRequest().authenticated() // 其他請求需認(rèn)證
.and()
.httpBasic(); // 啟用基本認(rèn)證
}
}步驟3:配置用戶名和密碼
Spring Boot 默認(rèn)會生成隨機用戶名和密碼。要使用自定義憑據(jù),可在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 端點
端點安全的最佳實踐:
• 最小化暴露端點:僅開放必要的端點,減少安全風(fēng)險。
• 使用角色權(quán)限控制:確保敏感端點只能由特定角色訪問。
• 啟用 HTTPS:在生產(chǎn)環(huán)境中,強制使用 HTTPS 保護數(shù)據(jù)傳輸安全。
• 結(jié)合 API 網(wǎng)關(guān)或身份認(rèn)證服務(wù):如 Keycloak、OAuth2 進行細粒度訪問控制。
通過以上安全策略,可以有效保護 Actuator 端點,確保監(jiān)控數(shù)據(jù)的安全性。
六、監(jiān)控與管理常用示例
Spring Boot Actuator 提供了豐富的端點,可用于監(jiān)控和管理應(yīng)用。下面介紹幾個常見的使用場景,幫助你在生產(chǎn)環(huán)境中高效監(jiān)控應(yīng)用狀態(tài)。
1. 健康檢查端點的應(yīng)用
健康檢查是 Actuator 最常用的功能之一,常用于:
• 應(yīng)用存活檢測:判斷服務(wù)是否正常運行,可用于負(fù)載均衡器的健康檢查。
• 外部依賴檢查:檢測數(shù)據(jù)庫、緩存、第三方 API 是否可用,保障系統(tǒng)穩(wěn)定性。
最佳實踐
• 自定義健康檢查
如,檢查數(shù)據(jù)庫狀態(tài)、MQ 消息隊列是否正常。
• 與負(fù)載均衡器集成
負(fù)載均衡器(如 Nginx、Kubernetes)可通過/actuator/health判斷服務(wù)健康狀態(tài),自動進行流量分配或故障轉(zhuǎn)移。
2.自定義度量指標(biāo)的應(yīng)用
Actuator 端點/actuator/metrics提供 JVM 運行時、線程池、HTTP 請求等性能指標(biāo)。可以使用MeterRegistry添加自定義度量指標(biāo)。
最佳實踐:
• 添加 API 請求計數(shù)、耗時統(tǒng)計:監(jiān)控接口調(diào)用頻率和性能瓶頸。
• 集成 Prometheus/Grafana:通過可視化工具實時查看度量數(shù)據(jù)。
3.日志管理擴展
日志是調(diào)試和運維的重要工具,Actuator 允許動態(tài)修改日志級別,無需重啟應(yīng)用。
最佳實踐:
• 生產(chǎn)環(huán)境下,日志級別默認(rèn)設(shè)置為 WARN 或 ERROR,僅記錄關(guān)鍵信息。
• 調(diào)試時,可動態(tài)調(diào)整為 DEBUG 級別,快速排查問題。
• 結(jié)合 ELK(Elasticsearch + Logstash + Kibana)等日志分析工具,提高故障診斷效率。
七、總結(jié)
1. 核心要點
• 集成 Spring Boot Actuator
提供開箱即用的監(jiān)控和管理功能,幫助監(jiān)控應(yīng)用健康和性能。
• 自定義和擴展端點
可根據(jù)業(yè)務(wù)需求定制健康檢查、度量指標(biāo)等,擴展 Actuator 的功能。
• 端點安全管理
使用 Spring Security 配置權(quán)限控制,確保端點訪問的安全性
到此這篇關(guān)于Spring Boot Actuator - 應(yīng)用監(jiān)控與管理的文章就介紹到這了,更多相關(guān)Spring Boot Actuator監(jiān)控內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
全面匯總SpringBoot和SpringClould常用注解
Java注解是附加在代碼中的一些元信息,用于一些工具在編譯、運行時進行解析和使用,起到說明、配置的功能,這篇文章就帶你來了解一下2021-08-08
如何利用SpringBoot搭建WebService服務(wù)接口
之前項目經(jīng)理想要開發(fā)一個webservice的協(xié)議,給我一個星期的時間,后面用springboot開發(fā)了webservice,這篇文章主要給大家介紹了關(guān)于如何利用SpringBoot搭建WebService服務(wù)接口的相關(guān)資料,需要的朋友可以參考下2023-11-11
SpringBoot整合Gson 整合Fastjson的實例詳解
這篇文章主要介紹了SpringBoot整合Gson 整合Fastjson的實例詳解,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
基于MockMvc進行springboot調(diào)試(SpringbootTest)
這篇文章主要介紹了基于MockMvc進行springboot調(diào)試(SpringbootTest),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10
SpringBoot使用開發(fā)環(huán)境application.properties問題
這篇文章主要介紹了SpringBoot使用開發(fā)環(huán)境application.properties問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07

