13.Spring boot中使用Actuator 監控
Spring Boot Actuator 是 Spring Boot 提供的一個強大的監控和管理工具,它通過暴露各種端點(Endpoints)來提供應用程序的運行時信息。這些端點可以幫助開發者和管理員監控應用程序的健康狀況、性能指標、環境信息等。
在生產環境中,建議僅啟用必要的端點,并啟用安全限制以防止未經授權的訪問。
敏感端點:某些端點(如 /actuator/env、/actuator/loggers)可能包含敏感信息,應謹慎處理。
建議結合 Spring Security 對 Actuator 端點進行訪問控制。
- 快速集成 Spring Boot Actuator。
- 自定義健康檢查和端點。
一、項目初始化
1. 項目結構
spring-boot-actuator-demo/
├── src/
│ ├── main/
│ │ ├── java/com/example/demo/
│ │ │ ├── DemoApplication.java # 固定名稱:主啟動類
│ │ │ ├── actuator/ # 自定義端點目錄(非固定,可選)
│ │ │ │ └── CustomEndpoint.java # 自定義端點類(非固定)
│ │ │ ├── health/ # 自定義健康檢查目錄(非固定,可選)
│ │ │ │ └── CustomHealthIndicator.java # 自定義健康檢查類(非固定)
│ │ │ └── config/ # 配置類目錄(非固定,可選)
│ │ │ └── SecurityConfig.java # Spring Security 配置類(非固定)
│ │ └── resources/
│ │ ├── application.yml # 固定名稱:主配置文件
│ │ └── application-prod.yml # 非固定名稱:生產環境配置(可選)
└── pom.xml # 固定名稱:Maven 依賴管理
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>spring-boot-actuator-demo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties><!-- Spring Boot 父級依賴(固定名稱,必須) --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.5</version> <!-- 使用最新穩定版本 --><relativePath/> <!-- 從倉庫查找,不繼承本地路徑 --></parent><dependencies><!-- Spring Boot Web 依賴(非固定名稱,按需添加) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Boot Actuator 依賴(非固定名稱,按需添加) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency></dependencies><!-- 構建配置(固定名稱,通常無需修改) --><build><plugins><!-- Spring Boot Maven 插件(固定名稱,必須) --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
創建主啟動類 DemoApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
二、分步實現
第一步:基礎 Actuator 集成(無需代碼)
目標:僅通過配置文件啟用 Actuator,并驗證默認端點。
-
修改
pom.xml
(固定名稱)
確保已添加spring-boot-starter-actuator
依賴:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId> </dependency>
-
配置
application.yml
(固定名稱)
啟用默認端點(如health
和info
):server:port: 8080management:endpoints:web:exposure:include: "health,info" # 僅暴露 health 和 info 端點
-
驗證
- 啟動應用,訪問:
http://localhost:8080/actuator/health
(返回{"status":"UP"}
)http://localhost:8080/actuator/info
(默認返回空對象{}
)
- 啟動應用,訪問:
暴露所有端點
第二步:自定義健康檢查(需代碼)
目標:添加一個自定義健康檢查邏輯(例如檢查外部服務狀態)。
-
更新
application.yml
(固定名稱)
配置健康檢查顯示詳細信息:management:endpoint:health:show-details: always # 顯示健康檢查的詳細信息
-
創建
CustomHealthIndicator.java
(非固定名稱,但需遵循包路徑)
在com.example.demo.health
包下創建類(包路徑可自定義,但需與代碼邏輯一致):import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component;@Component public class CustomHealthIndicator implements HealthIndicator {@Overridepublic Health health() {boolean isHealthy = checkExternalService(); // 模擬檢查邏輯if (isHealthy) {return Health.up().withDetail("status", "External service is healthy,健康的").build();} else {return Health.down().withDetail("error", "External service is unavailable").build();}}private boolean checkExternalService() {// 實際場景中替換為真實檢查邏輯(如 HTTP 請求、數據庫連接等)return true; // 示例中始終返回 true} }
- 驗證
- 訪問
http://localhost:8080/actuator/health
,返回結果將包含自定義健康檢查的詳細信息。
- 訪問
第三步:自定義端點(需代碼)
目標:添加一個自定義 Actuator 端點,支持 GET、POST 和 DELETE 操作。
-
創建
CustomEndpoint.java
(非固定名稱,但需遵循包路徑)
在com.example.demo.actuator
包下創建類(包路徑可自定義):import org.springframework.boot.actuate.endpoint.annotation.*; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.Map;@Component @Endpoint(id = "custom") // 端點 ID,訪問路徑為 /actuator/custom public class CustomEndpoint {// 只讀端點(GET 請求)@ReadOperationpublic Map<String, String> customData() {return Collections.singletonMap("message", "Hello from Custom Actuator Endpoint!");} }
-
更新
application.yml
(固定名稱)
暴露自定義端點:management:endpoints:web:exposure:include: "health,info,custom" # 添加 custom 端點
- 驗證
- GET 請求:
http://localhost:8080/actuator/custom
返回{"message":"Hello from Custom Actuator Endpoint!"}
- GET 請求:
三、核心配置文件說明
文件路徑 | 名稱是否固定 | 作用說明 |
---|---|---|
pom.xml | 固定 | Maven 依賴管理文件,定義項目依賴。 |
application.yml | 固定 | 主配置文件,定義 Actuator 端點暴露、安全配置等。 |
application-prod.yml | 非固定 | 生產環境配置(可選),通過 spring.profiles.active=prod 激活。 |
CustomHealthIndicator.java | 非固定 | 自定義健康檢查邏輯,覆蓋默認健康檢查行為。 |
CustomEndpoint.java | 非固定 | 自定義 Actuator 端點,支持 RESTful 操作(GET/POST/DELETE)。 |
四、生產環境建議
- 限制端點暴露
僅暴露必要端點(如health
,info
,metrics
):management:endpoints:web:exposure:include: "health,info,metrics"