![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5CMyEGOjhTOkFWOyATYldTM2EjMilDMjljN3gjMwQGMx8CXxIzLcdDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLzM3Lc9CX6MHc0RHaiojIsJye.png)
文章目錄
-
- 1. 前言
- 2. Spring Boot Admin
- 3. 快速內建
-
- 3.1 配置 Spring Boot Admin Server
- 3.2 配置 Spring Boot Admin
- 4. Spring Boot Admin 安全通路控制
-
- 4.1 保護 Spring Boot Admin Server 伺服器
-
- 添加 **Spring Security Starter** 依賴:
- 設定管理賬戶資訊
- 配置安全路徑通路控制
- 4.2 保護 Spring Boot Admin Client 端點
-
- 設定安全賬戶資訊
- 設定服務端安全賬戶資訊
- 保護 Actuator 端點
- 5. 進階實戰
-
- 5.1 日志檢視
- 5.2 按應用執行個體添加标簽
- 5.3 郵件通知
-
- 引入郵件依賴
- spring boot mail 配置
- Spring Boot Admin 郵件配置
- 6. 總結
生産上對
Web
應用 的監控是十分必要的。我們可以近乎實時來對應用的健康、性能等其他名額進行監控來及時應對一些突發情況。避免一些故障的發生。對于 Spring Boot 應用來說我們可以通過一個輕量級的監控工具 Spring Boot Admin (SBA) 來進行監控。
Spring Boot Admin是由德國軟體工程師 Johannes Edmeier 開源的用于管理和監控 Spring Boot 應用程式。已經被收納入Spring Initializr 截至發文時間的最新正式版本為 2.1.6 ,快照為2.2.0-SNAPSHOT。 C/S 架構風格 。 應用程式作為 Spring Boot Admin Client 向 Spring Boot Admin Server 注冊(通過
HTTP
)或使用 Spring Cloud注冊中心(如 Eureka,Consul)發現。SERVER程式采用了 響應式Web架構 Spring Webflux 。 展示UI采用了 Vue.js,展示Spring Boot Admin Client 通過 Spring Boot Actuator 端點上的一些監控。常見的功能或者監控如下:
- 顯示健康狀況
- 顯示應用度量名額詳情,例如
- JVM和記憶體名額
- micrometer度量
- 資料源名額
- 緩存名額
- 顯示建構資訊編号
- 關注并下載下傳日志檔案
- 下載下傳
heapdump
- 檢視
系統和環境屬性jvm
- 檢視 Spring Boot 配置屬性
- 支援 Spring Cloud 的環境端點和重新整理端點 ``
- 支援 K8s
- 易用的日志級别管理
- 與
互動JMX-beans
- 檢視線程轉儲
-
跟蹤http
-
auditevents
-
http-endpoints
- 檢視計劃任務
- 檢視和删除活動會話(使用 Spring Session )
-
/Flyway
資料庫遷移Liquibase
- 狀态變更通知(通過電子郵件,Slack,Hipchat等,支援釘釘)
- 狀态更改的事件日志(非持久化)
接下來讓我們來在 Spring Boot 項目中內建 Spring Boot Admin 。注意版本的相容性,可通過Spring Initializr 來驗證。
Spring Boot Admin Server 一般推薦獨立作為一個 Spring Boot
jar
應用運作。 隻需要将下列依賴添加到你的
pom.xml
中:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.2.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 生産需要保證監控的安全性-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
然後通過添加
@EnableAdminServer
到配置中來引入 Spring Boot Admin Server 配置:
@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminApplication.class, args);
}
}
每個要注冊的應用程式都必須包括 Spring Boot Admin Client。為了保護端點,你還應該添加安全依賴
spring-boot-starter-security
。
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
然後在用戶端應用程式的
application.yml
中增加以下配置:
spring:
boot:
admin:
client:
# Spring Boot Admin Server 位址 http://localhost:8080 可自定義
url: http://localhost:8080
# 預設情況下,大多數端點都不通過http公開,我們公開了所有端點。對于生産,您應該仔細選擇要公開的端點。
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: ALWAYS
分别啟動
SBA
服務端和用戶端 。打開服務端頁面
http://localhost:8080
将進入以下監控界面:
進而也可以擷取
admin-client
的具體監控名額:
如果您已經将 Spring Cloud Discovery (
eureka
、
consul
等)用于您的應用程式,則不需要 Spring Boot Admin 用戶端。隻需将 DiscoveryClient 添加到 Spring Boot Admin Server ,其餘的事情通過自動配置完成,可通過官方示例來檢視。
應用的監控名額都是極其敏感的資料。是以生産上必須增加安全通路控制以避免發生洩漏事件。你可以使用你擅長的安全架構來做通路控制。這裡我們采用 Spring Security 來保護我們的 Spring Boot Admin 。
添加 Spring Security Starter 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
spring:
security:
user:
name: SBA_admin
password: SBA_password
roles: SBA_ADMIN
package cn.felord.admin.server.configuer;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.util.UUID;
/**
* The type Security secure config.
*
* @author Felordcn
* @since 2019 /10/19 23:33
*/
@Configuration
public class AdminServerSecurityConfig extends WebSecurityConfigurerAdapter {
private final AdminServerProperties adminServer;
/**
* Instantiates a new Security secure config.
*
* @param adminServer the admin server
*/
public AdminServerSecurityConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
final String adminServerContextPath = this.adminServer.getContextPath();
successHandler.setDefaultTargetUrl(adminServerContextPath +"/");
http.authorizeRequests()
.antMatchers(adminServerContextPath + "/assets/**").permitAll() // <1>
.antMatchers(adminServerContextPath
+ "/login").permitAll()
.anyRequest().authenticated() // <2>
.and()
.formLogin().loginPage(adminServerContextPath + "/login").successHandler(successHandler).and() // <3>
.logout().logoutUrl(adminServerContextPath + "/logout").and()
.httpBasic().and() // <4>
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // <5>
.ignoringRequestMatchers(
new AntPathRequestMatcher(adminServerContextPath + "/instances", HttpMethod.POST.toString()), // <6>
new AntPathRequestMatcher(adminServerContextPath + "/instances/*", HttpMethod.DELETE.toString()), // <6>
new AntPathRequestMatcher(adminServerContextPath + "/actuator/**") // <7>
)
.and()
.rememberMe().key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600);
}
}
然後啟動 SBA Server 伺服器
http://localhost:8237
會進入登入頁面,輸入你配置的賬密即可:
服務端端點被通路控制後,用戶端注冊需要權限,同時用戶端的一些 Actuator 端點也必須被保護。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
spring:
security:
user:
name: SBA_admin
password: SBA_password
roles: SBA_ADMIN
将我們在Spring Boot Admin服務端配置配置的安全賬戶配置到以下屬性中:
spring:
boot:
admin:
client:
# Spring Boot Admin Server 管理賬戶
username: SBA_admin
password: SBA_password
當使用
HTTP Basic
身份驗證保護執行器端點時,SBA Server 需要憑據才能通路它們。是以我們通過以下來配置以授權服務端通路 Actuator 端點:
spring:
boot:
admin:
client:
instance:
metadata:
# 這裡是我們在 client 設定安全賬戶資訊 步驟中設定的賬密
user.name: ${spring.security.user.name}
user.password: ${spring.security.user.password}
啟動用戶端應用就可以了。
請注意:如果你改變了 HTTP BASIC 方式通路端點,上面的配置會失效,你可能會需要定制
HttpHeadersProvider
來滿足你的需要。
Spring Boot Admin 還提供了一些我們常用的功能。
預設情況下,日志檔案無法通過執行器端點通路,是以在 Spring Boot Admin 中不可見。為了啟用日志檔案執行器端點,您需要通過設定
logging.path
或
logging.file
Spring Boot Admin 将檢測所有看起來像URL的内容,并将其呈現為超連結。還支援
ANSI
顔色轉義。您需要設定一個自定義檔案日志模式,因為Spring Boot的預設模式不使用顔色。
以
logging.file
為例, 我們在用戶端
application.yml
增加以下配置:
logging:
file: /application.log
pattern:
file: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx'
然後即可在
SBA
控制台顯示:
Tags
是我們差別同一應用的不同執行個體的有效方法。比如我們同時使用
SBA
監控了
spring.application.name=admin-client
應用的三個執行個體,分别是開發(
DEV
)、測試(
TEST
)、生産(
PROD
)。我們可以通過(以開發為例):
使用資訊端點
/info
:
info:
tags:
environment: DEV
或者配置
SBA
中繼資料:
spring:
boot:
admin:
client:
instance:
metadata:
tags:
environment: DEV
然後我們就可以通過詳情界面檢視到具體的資訊:
Spring Boot Admin 支援配置郵件來發送郵件通知,以便于我們及時處置系統警報。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
# spring boot mail 配置
spring:
mail:
host: smtp.qq.com
username: [email protected]
password: password
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
# SBA 郵件配置
spring:
boot:
admin:
notify:
mail:
from: [email protected]
to: [email protected]
這樣就可以接收郵件告警了。國内也可以使用釘釘機器人通知功能。
還有其它一些功能,可以通過官方文檔進行學習。