1. 介紹
Spring Boot Actuator 是一個用于監控和管理 Spring Boot 應用程序的功能模塊。它提供了一系列生產就緒的功能,幫助你了解應用程序的運行狀況,以及在運行時對應用程序進行調整。Actuator 使用了 Spring MVC 來暴露各種 HTTP 或 JMX 端點,通過這些端點你可以獲取到應用程序的運行信息,如健康狀態、指標、線程 dump、環境變量等。
Spring Boot Actuator 的主要特性包括:
- 健康檢查:可以檢查應用程序的運行狀況,包括數據庫連接、磁盤空間、服務狀態等。
- 指標收集:收集應用程序的性能指標,如內存使用情況、處理器使用情況、HTTP 請求計數等。
- HTTP 端點:暴露了一系列的 HTTP 端點,通過這些端點可以訪問應用程序的運行信息。
- 日志管理:可以動態地修改應用程序的日志級別。
- 跟蹤和應用信息:提供了對應用程序的跟蹤信息和應用信息的訪問。
- 線程轉儲:可以獲取應用程序的線程轉儲信息,幫助診斷性能問題。
- 環境信息:可以查看應用程序的配置屬性和環境變量。
- 映射信息:可以查看 Spring MVC 的映射信息。
- 審計事件:可以訪問應用程序的審計事件信息。
要啟用 Spring Boot Actuator,你需要在項目中包含相應的依賴,然后在配置文件中配置相關的屬性。Spring Boot 2.x 版本中,Actuator 的默認端點是通過 HTTP 公開的,但是出于安全考慮,除了/health
和/info
端點之外,其他端點默認是不對外暴露的。你可以通過配置文件來開啟這些端點,并設置是否需要認證訪問。
Spring Boot Actuator 是開發和管理生產級 Spring Boot 應用程序的重要工具,它可以幫助你確保應用程序的穩定性和性能。
2. 問題描述
<!-- SpringBoot Actuator -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
當我們的項目只是引入了 actuator 模塊時,默認只公開了幾個接口,如:
訪問http://localhost:9200/actuator
有些情況下,我們需要將服務的健康信息上報給安全監控服務,則需要將接口打開
# 暴露監控端點
management:endpoints:web:exposure:include: '*'
此時,再次訪問http://localhost:9200/actuator
也可以訪問具體的屬性http://localhost:9200/actuator/env
我們發現這個時候就會暴露很多服務信息,安全性得不到保證。
3. 解決方案
3.1 springboot1.x
3.1.1 禁用所有端口
#關閉全部接口
endpoints.enabled = false###只開啟某些接口
#endpoints.beans.enabled = true
#endpoints.env.enabled = true
#endpoints.trace.enabled = true
#endpoints.metrics.enabled = true
3.1.2 安全框架控制
引入依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置輸入賬號密碼驗證后才允許訪問
management.security.enabled=true
security.user.name=admin
security.user.password=admin
3.2 springboot2.x
3.2.1 禁用所有端口
management.endpoints.enabled-by-default: false
3.2.2 安全框架控制
引入依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置輸入賬號密碼驗證后才允許訪問
spring.security.user.name=actuator
spring.security.user.password=actuator
添加配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/*** Actuator 監控端點權限**/
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {http.httpBasic().and().authorizeRequests().antMatchers("/actuator/**").authenticated().anyRequest().permitAll();http
// 關閉csrf token認證不需要csrf防護.csrf().disable()
// 關閉Session會話管理器 JWT 不需要.sessionManagement().disable()
// 關閉記住我功能 JWT 不需要.rememberMe().disable();}
}
4. 參考資料
https://zhuanlan.zhihu.com/p/602691208
https://springdoc.cn/spring-boot-actuator-enable-endpoints/
https://blog.csdn.net/weixin_44106034/article/details/133934404
https://developer.aliyun.com/article/1079170