【轉載請注明出處】: https://blog.csdn.net/huahao1989/article/details/108039738
1.概述
Spring Boot Admin是一個Web應用程式,用于管理和監視Spring Boot應用程式。每個應用程式都被視為用戶端,并注冊到管理伺服器。底層能力是由Spring Boot Actuator端點提供的。
在本文中,我們将介紹配置Spring Boot Admin伺服器的步驟以及應用程式如何內建用戶端。
2.管理伺服器配置
由于Spring Boot Admin Server可以作為servlet或webflux應用程式運作,根據需要,選擇一種并添加相應的Spring Boot Starter。在此示例中,我們使用Servlet Web Starter。
首先,建立一個簡單的Spring Boot Web應用程式,并添加以下Maven依賴項:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
之後,@ EnableAdminServer将可用,是以我們将其添加到主類中,如下例所示:
@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminServerApplication.class, args);
}
}
至此,服務端就配置完了。
3.設定用戶端
要在Spring Boot Admin Server伺服器上注冊應用程式,可以包括Spring Boot Admin用戶端或使用Spring Cloud Discovery(例如Eureka,Consul等)。
下面的例子使用Spring Boot Admin用戶端進行注冊,為了保護端點,還需要添加spring-boot-starter-security,添加以下Maven依賴項:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
接下來,我們需要配置用戶端說明管理伺服器的URL。為此,隻需添加以下屬性:
spring.boot.admin.client.url=http://localhost:8080
從Spring Boot 2開始,預設情況下不公開運作狀況和資訊以外的端點,對于生産環境,應該仔細選擇要公開的端點。
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
使執行器端點可通路:
@Configuration
public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll()
.and().csrf().disable();
}
}
為了簡潔起見,暫時禁用安全性。
如果項目中已經使用了Spring Cloud Discovery,則不需要Spring Boot Admin用戶端。隻需将DiscoveryClient添加到Spring Boot Admin Server,其餘的自動配置完成。
下面使用Eureka做例子,但也支援其他Spring Cloud Discovery方案。
将spring-cloud-starter-eureka添加到依賴中:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
通過添加@EnableDiscoveryClient到配置中來啟用發現
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
@EnableAdminServer
public class SpringBootAdminApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminApplication.class, args);
}
@Configuration
public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll()
.and().csrf().disable();
}
}
}
配置Eureka用戶端:
eureka:
instance:
leaseRenewalIntervalInSeconds: 10
health-check-url-path: /actuator/health
metadata-map:
startup: ${random.int} #需要在重新開機後觸發資訊和端點更新
client:
registryFetchIntervalSeconds: 5
serviceUrl:
defaultZone: ${EUREKA_SERVICE_URL:http://localhost:8761}/eureka/
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS
4.安全配置
Spring Boot Admin伺服器可以通路應用程式的敏感端點,是以建議為admin 服務和用戶端應用程式添加一些安全配置。
由于有多種方法可以解決分布式Web應用程式中的身份驗證和授權,是以Spring Boot Admin不會提供預設方法。預設情況下spring-boot-admin-server-ui提供登入頁面和登出按鈕。
伺服器的Spring Security配置如下所示:
@Configuration(proxyBeanMethods = false)
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
private final AdminServerProperties adminServer;
public SecuritySecureConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeRequests(
(authorizeRequests) -> authorizeRequests.antMatchers(this.adminServer.path("/assets/**")).permitAll()
// 授予對所有靜态資産和登入頁面的公共通路權限
.antMatchers(this.adminServer.path("/login")).permitAll().anyRequest().authenticated() //其他所有請求都必須經過驗證
).formLogin(
(formLogin) -> formLogin.loginPage(this.adminServer.path("/login")).successHandler(successHandler).and() //配置登入和登出
).logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout"))).httpBasic(Customizer.withDefaults()) //啟用HTTP基本支援,這是Spring Boot Admin Client注冊所必需的
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) //使用Cookies啟用CSRF保護
.ignoringRequestMatchers(
new AntPathRequestMatcher(this.adminServer.path("/instances"),
HttpMethod.POST.toString()),
new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
HttpMethod.DELETE.toString()), //禁用Spring Boot Admin Client用于(登出)注冊的端點的CSRF-Protection
new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))
)) //對執行器端點禁用CSRF-Protection。
.rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER");
}
}
添加之後,用戶端無法再向伺服器注冊。為了向伺服器注冊用戶端,必須在用戶端的屬性檔案中添加更多配置:
spring.boot.admin.client.username=admin
spring.boot.admin.client.password=admin
當使用HTTP Basic身份驗證保護執行器端點時,Spring Boot Admin Server需要憑據才能通路它們。可以在注冊應用程式時在中繼資料中送出憑據。在BasicAuthHttpHeaderProvider随後使用該中繼資料添加Authorization頭資訊來通路應用程式的執行端點。也可以提供自己的屬性HttpHeadersProvider來更改行為(例如添加一些解密)或添加額外的請求頭資訊。
使用Spring Boot Admin用戶端送出憑據:
spring.boot.admin.client:
url: http://localhost:8080
instance:
metadata:
user.name: ${spring.security.user.name}
user.password: ${spring.security.user.password}
使用Eureka送出憑據:
eureka:
instance:
metadata-map:
user.name: ${spring.security.user.name}
user.password: ${spring.security.user.password}
5.日志檔案檢視器
預設情況下,日志檔案無法通過執行器端點通路,是以在Spring Boot Admin中不可見。為了啟用日志檔案執行器端點,需要通過設定logging.file.path或将Spring Boot配置為寫入日志檔案 logging.file.name。
Spring Boot Admin将檢測所有看起來像URL的内容,并将其呈現為超連結。
還支援ANSI顔色轉義。因為Spring Boot的預設格式不使用顔色,可以設定一個自定義日志格式支援顔色。
logging.file.name=/var/log/sample-boot-application.log
logging.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
6. 通知事項
郵件通知
郵件通知将作為使用Thymeleaf模闆呈現的HTML電子郵件進行傳遞。要啟用郵件通知,請配置
JavaMailSender
使用
spring-boot-starter-mail
并設定收件人。
将spring-boot-starter-mail添加到依賴項中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置一個JavaMailSender
spring.mail.username=smtp_user
spring.mail.password=smtp_password
[email protected]
無論何時注冊用戶端将其狀态從“ UP”更改為“ OFFLINE”,都會将電子郵件發送到上面配置的位址。
自定義通知程式
可以通過添加實作Notifier接口的Spring Bean來添加自己的通知程式,最好通過擴充 AbstractEventNotifier或AbstractStatusChangeNotifier來實作。
public class CustomNotifier extends AbstractEventNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingNotifier.class);
public CustomNotifier(InstanceRepository repository) {
super(repository);
}
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
return Mono.fromRunnable(() -> {
if (event instanceof InstanceStatusChangedEvent) {
LOGGER.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(),
((InstanceStatusChangedEvent) event).getStatusInfo().getStatus());
}
else {
LOGGER.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(),
event.getType());
}
});
}
}
其他的一些配置參數和屬性可以通過
官方文檔來了解。
歡迎關注 “後端老鳥” 公衆号,接下來會發一系列的專題文章,包括Java、Python、Linux、SpringBoot、SpringCloud、Dubbo、算法、技術團隊的管理等,還有各種腦圖和學習資料,NFC技術、搜尋技術、爬蟲技術、推薦技術、音視訊互動直播等,隻要有時間我就會整理分享,敬請期待,現成的筆記、腦圖和學習資料如果大家有需求也可以公衆号留言提前擷取。由于本人在所有團隊中基本都處于攻堅和探路的角色,搞過的東西多,遇到的坑多,解決的問題也很多,歡迎大家加公衆号進群一起交流學習。