生產上對 Web
應用 的監控是十分必要的。咱們能夠近乎實時來對應用的健康、性能等其餘指標進行監控來及時應對一些突發狀況。避免一些故障的發生。對於 Spring Boot 應用來講咱們能夠經過一個輕量級的監控工具 Spring Boot Admin (SBA) 來進行監控。html
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 端點上的一些監控。常見的功能或者監控以下:java
顯示應用度量指標詳情,例如web
heapdump
jvm
系統和環境屬性JMX-beans
交互http
跟蹤auditevents
http-endpoints
Flyway
/Liquibase
數據庫遷移接下來讓咱們來在 Spring Boot 項目中集成 Spring Boot Admin 。注意版本的兼容性,可經過Spring Initializr 來驗證。spring
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
中增長如下配置:springboot
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 。
<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服務端配置配置的安全帳戶配置到如下屬性中:
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([%15.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: username@xx.com password: password properties: mail: smtp: auth: true starttls: enable: true required: true
# SBA 郵件配置 boot: admin: notify: mail: from: from_user@xxx.com to: to_admin@xxx.com
這樣就能夠接收郵件告警了。國內也可使用釘釘機器人通知功能。
還有其它一些功能,能夠經過官方文檔進行學習。
今天咱們學習了使用 Spring Boot Admin 對 Spring Boot 應用進行監控。也學習瞭如何對 Spring Boot Admin 進行安全訪問控制,還有一些有用的進階操做。
這裏須要說明的是對一些小型應用 Spring Boot Admin 能夠徹底勝任監控功能,也很是簡單好用。
可是對於大型分佈式集羣應用來講我我的不建議使用 Spring Boot Admin ,須要其它更加專業的 APM
監控,好比開源的 Apache Skywalking
、Prometheus + Grafana
等等。
相關 SBA
實戰完整代碼可關注公衆號:Felordcn
回覆 admin
獲取
關注公衆號:Felordcn獲取更多資訊