Spring Boot Admin排坑指南
Spring Boot Admin 1.x其簡陋的頁面讓人不忍直視,但更新到2.x系列後,像脫胎換骨一般好用
這篇部落格記錄我個人在使用Spring Boot Admin過程中遇到過的坑,每個坑位都會附上詳細的填坑辦法
環境引數:
-
Spring Boot 2.x
-
Spring Boot Admin 2.x
-
JDK1.8+
-
CentOS
服務直接註冊失敗
常見的註冊失敗問題可以分為以下兩種
-
Spring Boot Admin服務端與客戶端不在同一臺伺服器上
-
提示安全校驗不通過
第一種問題的解決辦法:
必須在客戶端配置boot.admin.client.instance.service-url屬性,讓Spring Boot Admin服務端可以通過網路獲取客戶端的資料(否則預設會通過主機名去獲取)
boot:
admin:
client:
url: ${your spring boot admin url}
username: ${your spring boot admin username}
password: ${your spring boot admin password}
instance:
prefer-ip: true
service-url: ${your spring boot client url}
第二種問題的解決辦法:
首先,安全檢驗問題,其實就是現在服務端配置賬號密碼,然後客戶端在註冊的時候提供賬號密碼進行登入來完成校驗
這個過程的實現,作為Spring全家桶專案,推薦使用Spring Security來解決,所以如果出現校驗失敗,那多半是Spring Security的配置出現問題
接下來介紹如何分別配置服務端與客戶端來處理這個問題
服務端配置
通過maven載入Spring Security依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
設定服務端的使用者名稱和密碼(客戶端來註冊時使用此賬號密碼進行登入)
spring:
security:
user:
name: liumapp
password: superliumapp
編寫Spring Security配置類
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
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;
/**
* file SecuritySecureConfig.java
* author liumapp
* github https://github.com/liumapp
* email [email protected]
* homepage http://www.liumapp.com
* date 2018/11/29
*/
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
private final String adminContextPath;
public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
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()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers(
adminContextPath + "/instances",
adminContextPath + "/actuator/**"
);
// @formatter:on
}
}
上面這段程式碼,需要大家注意的就一個AdminServerProperties類,通過瀏覽它的部分原始碼:
@ConfigurationProperties("spring.boot.admin")
public class AdminServerProperties {
/**
* The context-path prefixes the path where the Admin Servers statics assets and api should be
* served. Relative to the Dispatcher-Servlet.
*/
private String contextPath = "";
/**
* The metadata keys which should be sanitized when serializing to json
*/
private String[] metadataKeysToSanitize = new String[]{".*password$", ".*secret$", ".*key$", ".*$token$", ".*credentials.*", ".*vcap_services$"};
/**
* For Spring Boot 2.x applications the endpoints should be discovered automatically using the actuator links.
* For Spring Boot 1.x applications SBA probes for the specified endpoints using an OPTIONS request.
* If the path differs from the id you can specify this as id:path (e.g. health:ping).
*/
private String[] probedEndpoints = {"health", "env", "metrics", "httptrace:trace", "httptrace", "threaddump:dump", "threaddump", "jolokia", "info", "logfile", "refresh", "flyway", "liquibase", "heapdump", "loggers", "auditevents", "mappings", "scheduledtasks", "configprops", "caches", "beans"};
//以下省略...
}
可以發現AdminServerProperties定義了Spring Boot Admin的配置屬性,登入自然也是其中之一,所以我們在編寫Spring Security配置類的時候,務必要引入AdminServerProperties
到這裡,Spring Boot Admin服務端對於Spring Security的配置便結束了,接下來讓我們開始客戶端的Security配置
客戶端配置
首先對於客戶端,我們除了Spring Boot Admin Client依賴外,還需要額外引入 Spring Security依賴:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
在此基礎上通過編寫客戶端application.yml配置檔案來設定賬號密碼
spring:
boot:
admin:
client:
url: ${your sba server url}
username: ${your sba username}
password: ${your sba password}
instance:
service-base-url: ${your client url}
接下來對Client端的Spring Security做配置,允許Server端讀取actuator暴露的資料
新增一個配置類:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll()
.and().csrf().disable();
}
}
到此,因為安全驗證而不能註冊成功的問題便可以解決
註冊成功但無法顯示日誌
這個問題產生原因有兩種
-
客戶端日誌沒有以檔案形式儲存下來
-
客戶端容器化部署後,日誌檔案沒有對映到宿主機磁碟上
針對第一種情況,解決辦法比較簡單,將系統產生的日誌以檔案形式儲存即可:
logging:
file: ./log/client.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"
第二種情況較為複雜,首先要分清除是用什麼工具來部署容器的,但一般而言直接通過檔案對映即可
這裡以docker為例,在docker內通過設定volumes來對映日誌檔案
volumes:
- ./log:/client/log/
註冊成功但資訊顯示不全
偶爾也會遇到這種情況:Spring Boot Admin客戶端註冊服務端是成功的,但是統計頁面顯示的資料過少(可能只有日誌這一欄)
造成這種問題的原因在於:我們沒有開放客戶端的actuator介面地址給服務端訪問
那麼解決辦法也很簡單,允許服務端訪問actuator即可
首先我們需要確保專案有actuator依賴(一般來說,spring-boot-admin-starter-client本身就包含這個依賴,所以不需要額外引入):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
然後開啟actuator的埠,在client端的配置檔案中增加以下內容:
management:
endpoints:
web:
exposure:
include: "*"
同時考慮到client與server域名存在不一樣的情況,順便把跨域也解決掉,增加跨域配置類:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author liumapp
* @file CorsConfig.java
* @email [email protected]
* @homepage http://www.liumapp.com
* @date 2018/8/11
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedOrigins("*")
.allowedMethods("*");
}
}