一起來學 SpringBoot 2.x | 第十五篇:actuator 與 spring-boot-admin 可以說的秘密

  • 2019 年 10 月 29 日
  • 筆記

來源:http://t.cn/EwMgr3F

  • 什麼是SBA
  • 導入依賴
  • 屬性配置
  • 描述資訊
    • 主函數
    • 測試
  • 總結
  • 說點什麼

SpringBoot 是為了簡化 Spring 應用的創建、運行、調試、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程

一起來學SpringBoot | 第十四篇:強大的 actuator 服務監控與管理 中介紹了actuator 的作用,細心的朋友可能會發現通過http restful api的方式查看資訊過於繁瑣也不夠直觀,效率低下,運維人員看到JSON數據更是一臉懵逼,當服務過多的時候查看起來就過於操蛋了,每個服務都需要調用不同的介面來查看監控資訊,備受各種困擾因素的我默默翻了下全球最大男性交友平台找到了spring-boot-admin

什麼是SBA

SBA 全稱 Spring Boot Admin 是一個管理和監控 Spring Boot 應用程式的開源項目。分為admin-server 與 admin-client 兩個組件,admin-server通過採集 actuator 端點數據,顯示在 spring-boot-admin-ui 上,已知的端點幾乎都有進行採集,通過 spring-boot-admin 可以動態切換日誌級別、導出日誌、導出heapdump、監控各項指標 等等….

Spring Boot Admin 在對單一應用服務監控的同時也提供了集群監控方案,支援通過eurekaconsulzookeeper等註冊中心的方式實現多服務監控與管理…

導入依賴

pom.xml 中添加 spring-boot-admin 的相關依賴,這裡只演示單機版本的,因此就自己監控自己了

<dependencies>      <!-- 服務端:帶UI介面 -->      <dependency>          <groupId>de.codecentric</groupId>          <artifactId>spring-boot-admin-starter-server</artifactId>          <version>2.0.0</version>      </dependency>      <!-- 客戶端包 -->      <dependency>          <groupId>de.codecentric</groupId>          <artifactId>spring-boot-admin-starter-client</artifactId>          <version>2.0.0</version>      </dependency>      <!-- 安全認證 -->      <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-security</artifactId>      </dependency>      <!-- 端點 -->      <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-actuator</artifactId>      </dependency>      <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-web</artifactId>      </dependency>      <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-test</artifactId>          <scope>test</scope>      </dependency>      <!-- 在管理介面中與 JMX-beans 進行交互所需要被依賴的 JAR -->      <dependency>          <groupId>org.jolokia</groupId>          <artifactId>jolokia-core</artifactId>      </dependency>  </dependencies>  

注意事項

如果要訪問info介面想獲取maven中的屬性內容請記得添加如下內容

<build>      <plugins>          <plugin>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-maven-plugin</artifactId>              <executions>                  <execution>                      <goals>                          <goal>build-info</goal>                      </goals>                  </execution>              </executions>          </plugin>      </plugins>  </build>  

屬性配置

application.properties 文件中配置actuator的相關配置,其中info開頭的屬性,就是訪問info端點中顯示的相關內容,值得注意的是Spring Boot2.x中,默認只開放了info、health兩個端點,剩餘的需要自己通過配置management.endpoints.web.exposure.include屬性來載入(有include自然就有exclude,不做詳細概述了)。這個management.endpoints.web.base-path屬性比較重要,因為Spring Boot2.x後每個端點默認的路徑是/actuator/endpointId這樣一來Spring Boot Admin是無法正常採集的

application.properties

# 描述資訊  info.blog-url=http://blog.battcn.com  info.author=Levin  # 如果 Maven 插件沒配置此處請注釋掉  [email protected]@  [email protected]@  # 選擇激活對應環境的配置,如果是dev則代表不用認證就能訪問監控頁,prod代表需要認證  spring.profiles.active=prod    # 日誌文件  logging.file=./target/admin-server.log    # 載入所有的端點/默認只載入了 info / health  management.endpoints.web.exposure.include=*  # 比較重要,默認 /actuator spring-boot-admin 掃描不到  management.endpoints.web.base-path=/  management.endpoint.health.show-details=always    spring.boot.admin.client.url=http://localhost:8080  # 不配置老喜歡用主機名,看著不舒服....  spring.boot.admin.client.instance.prefer-ip=true  

application-dev.properties – 空 application-prod.properties

為了安全起見,應採用認證的方式

# 登陸所需的帳號密碼  spring.security.user.name=battcn  spring.security.user.password=battcn  # 便於客戶端可以在受保護的伺服器上註冊api  spring.boot.admin.client.username=battcn  spring.boot.admin.client.password=battcn  # 便伺服器可以訪問受保護的客戶端端點  spring.boot.admin.client.instance.metadata.user.name=battcn  spring.boot.admin.client.instance.metadata.user.password=battcn  

主函數

添加上 @EnableAdminServer 註解即代表是Server端,集成UI的

package com.battcn;    import de.codecentric.boot.admin.server.config.AdminServerProperties;  import de.codecentric.boot.admin.server.config.EnableAdminServer;  import org.springframework.boot.SpringApplication;  import org.springframework.boot.autoconfigure.SpringBootApplication;  import org.springframework.context.annotation.Configuration;  import org.springframework.context.annotation.Profile;  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;      /**   * @author Levin   */  @SpringBootApplication  @EnableAdminServer  public class Chapter14Application {        public static void main(String[] args) {          SpringApplication.run(Chapter14Application.class, args);      }        /**       * dev 環境載入       */      @Profile("dev")      @Configuration      public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {          @Override          protected void configure(HttpSecurity http) throws Exception {              http.authorizeRequests().anyRequest().permitAll()                      .and().csrf().disable();          }      }        /**       * prod 環境載入       */      @Profile("prod")      @Configuration      public static class SecuritySecureConfig extends WebSecurityConfigurerAdapter {          private final String adminContextPath;            public SecuritySecureConfig(AdminServerProperties adminServerProperties) {              this.adminContextPath = adminServerProperties.getContextPath();          }            @Override          protected void configure(HttpSecurity http) throws Exception {              SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();              successHandler.setTargetUrlParameter("redirectTo");                http.authorizeRequests()                      .antMatchers(adminContextPath + "/assets/**").permitAll()                      .antMatchers(adminContextPath + "/login").permitAll()                      .anyRequest().authenticated()                      .and()                      .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()                      .logout().logoutUrl(adminContextPath + "/logout").and()                      .httpBasic().and()                      .csrf().disable();          }      }  }  

測試

完成準備事項後,啟動Chapter14Application 訪問 http://localhost:8080/login 看到登陸頁面則代表一切正常,接著輸入帳號密碼點擊登陸即可…

首頁

由於篇幅原因大圖就不放太多了,有興趣的朋友可以直接fork程式碼運行即可

總結

參考文檔:http://codecentric.github.io/spring-boot-admin/2.0.0/

目前很多大佬都寫過關於 SpringBoot 的教程了,如有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent:2.0.2.RELEASE編寫,包括新版本的特性都會一起介紹…

說點什麼

全文程式碼:https://github.com/battcn/spring-boot2-learning/tree/master/chapter14