1. 概述
Spring Boot Admin 是一款用於管理和監控 Spring Boot 應用的 Web 應用程序。每個應用程序都被視為客户端,並向管理服務器註冊。在幕後,Spring Boot Actuator 端點提供了這其中的“魔法”。
在本文中,我們將描述配置 Spring Boot Admin 服務器以及應用程序如何成為客户端的步驟。
2. 管理服務器設置
首先,我們需要創建一個簡單的 Spring Boot Web 應用程序,並添加以下 Maven 依賴項:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>3.1.5</version>
</dependency>之後,@EnableAdminServer</em/> 將可用,因此我們將將其添加到主類中,如下面的示例所示:
@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminServerApplication(exclude = AdminServerHazelcastAutoConfiguration.class) {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminServerApplication.class, args);
}
}此時,我們準備好啓動服務器並註冊客户端應用程序。
3. 設置客户端
現在,在設置好我們的管理服務器後,我們可以將第一個 Spring Boot 應用程序註冊為客户端。 我們需要添加以下 Maven 依賴項:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>3.1.5</version>
</dependency>接下來,我們需要配置客户端知道管理服務器的基礎 URL。要實現這一點,我們只需添加以下屬性:
spring.boot.admin.client.url=http://localhost:8080從 Spring Boot 2 開始,除了 health 和 info 之外的端點默認不暴露。
現在我們來暴露所有端點:
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always4. 安全配置
Spring Boot Admin 服務器可以訪問應用程序的敏感端點,因此建議我們在管理服務器和客户端應用程序中添加一些安全配置。
首先,我們將重點配置管理服務器的安全。我們需要添加以下 Maven 依賴項:。
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>1.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>3.1.5</version>
</dependency>這將啓用安全功能併為管理應用程序添加登錄界面。請務必獲取管理應用程序的最新版本:https://mvnrepository.com/artifact/de.codecentric/spring-boot-admin-server-ui。
接下來,我們將添加一個安全配置類,如以下所示:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
private final AdminServerProperties adminServer;
public WebSecurityConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.getContextPath() + "/");
http.authorizeHttpRequests(req -> req.requestMatchers(this.adminServer.getContextPath() + "/assets/**")
.permitAll()
.requestMatchers(this.adminServer.getContextPath() + "/login")
.permitAll()
.anyRequest()
.authenticated())
.formLogin(formLogin -> formLogin.loginPage(this.adminServer.getContextPath() + "/login")
.successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(this.adminServer.getContextPath() + "/logout"))
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
new AntPathRequestMatcher(this.adminServer.getContextPath() + "/instances", HttpMethod.POST.toString()),
new AntPathRequestMatcher(this.adminServer.getContextPath() + "/instances/*", HttpMethod.DELETE.toString()),
new AntPathRequestMatcher(this.adminServer.getContextPath() + "/actuator/**")))
.rememberMe(rememberMe -> rememberMe.key(UUID.randomUUID()
.toString())
.tokenValiditySeconds(1209600));
return http.build();
}
}存在一個簡單的安全配置,但添加後,我們發現客户端無法再向服務器註冊。
為了將客户端註冊到新的安全服務器,我們需要在客户端的屬性文件中添加更多配置:
spring.boot.admin.client.username=admin
spring.boot.admin.client.password=admin我們已經成功配置了管理服務器。在生產系統中,我們自然需要對運行的應用程序進行安全保護。因此,我們將為客户端添加安全措施,並在管理服務器的UI界面上,不再顯示客户端信息。
我們需要添加一些元數據,這些信息將被髮送到管理服務器,用於連接客户端端點:
spring.security.user.name=client
spring.security.user.password=client
spring.boot.admin.client.instance.metadata.user.name=${spring.security.user.name}
spring.boot.admin.client.instance.metadata.user.password=${spring.security.user.password}通過HTTP發送憑據當然不安全——因此,通信必須通過HTTPS進行。
5. 監控與管理功能
Spring Boot Admin 可以配置為僅顯示我們認為有用的信息。我們只需修改默認配置並添加我們需要的指標:
spring.boot.admin.routes.endpoints=env, metrics, trace, jolokia, info, configprops隨着我們深入研究,我們會發現還有一些其他功能可以探索。我們指的是JMX Bean 管理,使用 Jolokia,以及 日誌級別管理。
Spring Boot Admin 還支持使用 Hazelcast 的集羣複製。只需添加以下 Maven 依賴項,讓自動配置完成其餘工作:
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>4.0.3</version>
</dependency>如果想要使用 Hazelcast 的持久實例,我們將使用自定義配置:
@Configuration
public class HazelcastConfig {
@Bean
public Config hazelcast() {
MapConfig eventStoreMap = new MapConfig("spring-boot-admin-event-store")
.setInMemoryFormat(InMemoryFormat.OBJECT)
.setBackupCount(1)
.setEvictionConfig(new EvictionConfig().setEvictionPolicy(EvictionPolicy.NONE))
.setMergePolicyConfig(new MergePolicyConfig(PutIfAbsentMergePolicy.class.getName(), 100));
MapConfig sentNotificationsMap = new MapConfig("spring-boot-admin-application-store")
.setInMemoryFormat(InMemoryFormat.OBJECT)
.setBackupCount(1)
.setEvictionConfig(new EvictionConfig().setEvictionPolicy(EvictionPolicy.LRU))
.setMergePolicyConfig(new MergePolicyConfig(PutIfAbsentMergePolicy.class.getName(), 100));
Config config = new Config();
config.addMapConfig(eventStoreMap);
config.addMapConfig(sentNotificationsMap);
config.setProperty("hazelcast.jmx", "true");
config.getNetworkConfig()
.getJoin()
.getMulticastConfig()
.setEnabled(false);
TcpIpConfig tcpIpConfig = config.getNetworkConfig()
.getJoin()
.getTcpIpConfig();
tcpIpConfig.setEnabled(true);
tcpIpConfig.setMembers(Collections.singletonList("127.0.0.1"));
return config;
}
}6. 通知
接下來,我們討論一下如果我們的註冊客户端發生任何問題,是否可以從管理服務器接收通知的可能性。以下通知器可用於配置:
- 電子郵件
- PagerDuty
- OpsGenie
- Hipchat
- Slack
- Let’s Chat
6.1. 郵件通知
我們將首先重點配置管理服務器的郵件通知。為了實現這一點,我們需要添加 郵件啓動依賴項,如下所示:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.4.0</version>
</dependency>之後,我們需要添加一些郵件配置:
spring.mail.host=smtp.example.com
spring.mail.username=smtp_user
spring.mail.password=smtp_password
[email protected]現在,當我們的註冊客户狀態從“UP”更改為“OFFLINE”或其他狀態時,都會向配置好的地址發送一封電子郵件。對於其他通知者,配置方式類似。
6.2. Hipchat 通知
正如你所見,與 Hipchat 的集成相當簡單;只有少數必選屬性需要設置:
spring.boot.admin.notify.hipchat.auth-token=<generated_token>
spring.boot.admin.notify.hipchat.room-id=<room-id>
spring.boot.admin.notify.hipchat.url=https://yourcompany.hipchat.com/v2/有了這些定義,我們會在 Hipchat 房間中注意到,當客户端狀態發生變化時,會收到通知。
6.3. 定製通知配置
我們可以配置一個自定義通知系統,並利用一些強大的工具。我們可以使用一個提醒通知器,以便在客户端狀態發生變化時發送計劃好的通知。
或者,我們可能希望向一組篩選後的客户端發送通知。為此,我們可以使用一個過濾通知器:
@Configuration
public class NotifierConfiguration {
private final InstanceRepository repository;
private final ObjectProvider<List<Notifier>> otherNotifiers;
public NotifierConfiguration(InstanceRepository repository,
ObjectProvider<List<Notifier>> otherNotifiers) {
this.repository = repository;
this.otherNotifiers = otherNotifiers;
}
@Bean
public FilteringNotifier filteringNotifier() {
CompositeNotifier delegate =
new CompositeNotifier(this.otherNotifiers.getIfAvailable(Collections::emptyList));
return new FilteringNotifier(delegate, this.repository);
}
@Bean
public LoggingNotifier notifier() {
return new LoggingNotifier(repository);
}
@Primary
@Bean(initMethod = "start", destroyMethod = "stop")
public RemindingNotifier remindingNotifier() {
RemindingNotifier remindingNotifier = new RemindingNotifier(filteringNotifier(), repository);
remindingNotifier.setReminderPeriod(Duration.ofMinutes(5));
remindingNotifier.setCheckReminderInverval(Duration.ofSeconds(60));
return remindingNotifier;
}
}7. 結論
本教程介紹了使用 Spring Boot Admin 監控和管理 Spring Boot 應用程序的簡單步驟。
自動配置允許我們僅添加少量配置,最終就能擁有一個完全運行的 Admin 服務器。