詳解用Spring Boot Admin來(lái)監(jiān)控我們的微服務(wù)
1.概述
Spring Boot Admin是一個(gè)Web應(yīng)用程序,用于管理和監(jiān)視Spring Boot應(yīng)用程序。每個(gè)應(yīng)用程序都被視為客戶端,并注冊(cè)到管理服務(wù)器。底層能力是由Spring Boot Actuator端點(diǎn)提供的。
在本文中,我們將介紹配置Spring Boot Admin服務(wù)器的步驟以及應(yīng)用程序如何集成客戶端。
2.管理服務(wù)器配置
由于Spring Boot Admin Server可以作為servlet或webflux應(yīng)用程序運(yùn)行,根據(jù)需要,選擇一種并添加相應(yīng)的Spring Boot Starter。在此示例中,我們使用Servlet Web Starter。
首先,創(chuàng)建一個(gè)簡(jiǎn)單的Spring Boot Web應(yīng)用程序,并添加以下Maven依賴項(xiàng):
<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); } }
至此,服務(wù)端就配置完了。
3.設(shè)置客戶端
要在Spring Boot Admin Server服務(wù)器上注冊(cè)應(yīng)用程序,可以包括Spring Boot Admin客戶端或使用Spring Cloud Discovery(例如Eureka,Consul等)。
下面的例子使用Spring Boot Admin客戶端進(jìn)行注冊(cè),為了保護(hù)端點(diǎn),還需要添加spring-boot-starter-security,添加以下Maven依賴項(xiàng):
<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>
接下來(lái),我們需要配置客戶端說(shuō)明管理服務(wù)器的URL。為此,只需添加以下屬性:
spring.boot.admin.client.url=http://localhost:8080
從Spring Boot 2開始,默認(rèn)情況下不公開運(yùn)行狀況和信息以外的端點(diǎn),對(duì)于生產(chǎn)環(huán)境,應(yīng)該仔細(xì)選擇要公開的端點(diǎn)。
management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always
使執(zhí)行器端點(diǎn)可訪問(wèn):
@Configuration public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().permitAll() .and().csrf().disable(); } }
為了簡(jiǎn)潔起見,暫時(shí)禁用安全性。
如果項(xiàng)目中已經(jīng)使用了Spring Cloud Discovery,則不需要Spring Boot Admin客戶端。只需將DiscoveryClient添加到Spring Boot Admin Server,其余的自動(dòng)配置完成。
下面使用Eureka做例子,但也支持其他Spring Cloud Discovery方案。
將spring-cloud-starter-eureka添加到依賴中:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
通過(guò)添加@EnableDiscoveryClient到配置中來(lái)啟用發(fā)現(xiàn)
@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} #需要在重啟后觸發(fā)信息和端點(diǎn)更新 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服務(wù)器可以訪問(wèn)應(yīng)用程序的敏感端點(diǎn),因此建議為admin 服務(wù)和客戶端應(yīng)用程序添加一些安全配置。
由于有多種方法可以解決分布式Web應(yīng)用程序中的身份驗(yàn)證和授權(quán),因此Spring Boot Admin不會(huì)提供默認(rèn)方法。默認(rèn)情況下spring-boot-admin-server-ui提供登錄頁(yè)面和注銷按鈕。
服務(wù)器的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() // 授予對(duì)所有靜態(tài)資產(chǎn)和登錄頁(yè)面的公共訪問(wèn)權(quán)限 .antMatchers(this.adminServer.path("/login")).permitAll().anyRequest().authenticated() //其他所有請(qǐng)求都必須經(jīng)過(guò)驗(yàn)證 ).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注冊(cè)所必需的 .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) //使用Cookies啟用CSRF保護(hù) .ignoringRequestMatchers( new AntPathRequestMatcher(this.adminServer.path("/instances"), HttpMethod.POST.toString()), new AntPathRequestMatcher(this.adminServer.path("/instances/*"), HttpMethod.DELETE.toString()), //禁用Spring Boot Admin Client用于(注銷)注冊(cè)的端點(diǎn)的CSRF-Protection new AntPathRequestMatcher(this.adminServer.path("/actuator/**")) )) //對(duì)執(zhí)行器端點(diǎn)禁用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"); } }
添加之后,客戶端無(wú)法再向服務(wù)器注冊(cè)。為了向服務(wù)器注冊(cè)客戶端,必須在客戶端的屬性文件中添加更多配置:
spring.boot.admin.client.username=admin spring.boot.admin.client.password=admin
當(dāng)使用HTTP Basic身份驗(yàn)證保護(hù)執(zhí)行器端點(diǎn)時(shí),Spring Boot Admin Server需要憑據(jù)才能訪問(wèn)它們??梢栽谧?cè)應(yīng)用程序時(shí)在元數(shù)據(jù)中提交憑據(jù)。在BasicAuthHttpHeaderProvider隨后使用該元數(shù)據(jù)添加Authorization頭信息來(lái)訪問(wèn)應(yīng)用程序的執(zhí)行端點(diǎn)。也可以提供自己的屬性HttpHeadersProvider來(lái)更改行為(例如添加一些解密)或添加額外的請(qǐng)求頭信息。
使用Spring Boot Admin客戶端提交憑據(jù):
spring.boot.admin.client: url: http://localhost:8080 instance: metadata: user.name: ${spring.security.user.name} user.password: ${spring.security.user.password}
使用Eureka提交憑據(jù):
eureka: instance: metadata-map: user.name: ${spring.security.user.name} user.password: ${spring.security.user.password}
5.日志文件查看器
默認(rèn)情況下,日志文件無(wú)法通過(guò)執(zhí)行器端點(diǎn)訪問(wèn),因此在Spring Boot Admin中不可見。為了啟用日志文件執(zhí)行器端點(diǎn),需要通過(guò)設(shè)置logging.file.path或?qū)pring Boot配置為寫入日志文件 logging.file.name。
Spring Boot Admin將檢測(cè)所有看起來(lái)像URL的內(nèi)容,并將其呈現(xiàn)為超鏈接。
還支持ANSI顏色轉(zhuǎn)義。因?yàn)镾pring Boot的默認(rèn)格式不使用顏色,可以設(shè)置一個(gè)自定義日志格式支持顏色。
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. 通知事項(xiàng)
郵件通知
郵件通知將作為使用Thymeleaf模板呈現(xiàn)的HTML電子郵件進(jìn)行傳遞。要啟用郵件通知,請(qǐng)配置JavaMailSender使用spring-boot-starter-mail并設(shè)置收件人。
將spring-boot-starter-mail添加到依賴項(xiàng)中:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
配置一個(gè)JavaMailSender
spring.mail.username=smtp_user spring.mail.password=smtp_password spring.boot.admin.notify.mail.to=admin@example.com
無(wú)論何時(shí)注冊(cè)客戶端將其狀態(tài)從“ UP”更改為“ OFFLINE”,都會(huì)將電子郵件發(fā)送到上面配置的地址。
自定義通知程序
可以通過(guò)添加實(shí)現(xiàn)Notifier接口的Spring Bean來(lái)添加自己的通知程序,最好通過(guò)擴(kuò)展 AbstractEventNotifier或AbstractStatusChangeNotifier來(lái)實(shí)現(xiàn)。
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()); } }); } }
其他的一些配置參數(shù)和屬性可以通過(guò)官方文檔來(lái)了解。
到此這篇關(guān)于詳解用Spring Boot Admin來(lái)監(jiān)控我們的微服務(wù)的文章就介紹到這了,更多相關(guān)Spring Boot Admin監(jiān)控微服務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot整合Spring?Boot?Admin實(shí)現(xiàn)服務(wù)監(jiān)控的方法
- SpringBoot-Admin實(shí)現(xiàn)微服務(wù)監(jiān)控+健康檢查+釘釘告警
- 如何用Springboot Admin監(jiān)控你的微服務(wù)應(yīng)用
- 使用spring-boot-admin對(duì)spring-boot服務(wù)進(jìn)行監(jiān)控的實(shí)現(xiàn)方法
- 詳解Spring boot Admin 使用eureka監(jiān)控服務(wù)
- 詳解Spring Boot Admin監(jiān)控服務(wù)上下線郵件通知
- Spring?boot?admin?服務(wù)監(jiān)控利器詳解
相關(guān)文章
Feign?日期格式轉(zhuǎn)換錯(cuò)誤的問(wèn)題
這篇文章主要介紹了Feign?日期格式轉(zhuǎn)換錯(cuò)誤的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Java如何加載外部Jar的類并通過(guò)反射調(diào)用類的方法
這篇文章主要介紹了Java如何加載外部Jar的類并通過(guò)反射調(diào)用類的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06dubbo如何實(shí)現(xiàn)consumer從多個(gè)group中調(diào)用指定group的provider
這篇文章主要介紹了dubbo如何實(shí)現(xiàn)consumer從多個(gè)group中調(diào)用指定group的provider問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03Java算法練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(2)
方法下面小編就為大家?guī)?lái)一篇Java算法的一道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-07-07Java8 使用工廠方法supplyAsync創(chuàng)建CompletableFuture實(shí)例
這篇文章主要介紹了Java8 使用工廠方法supplyAsync創(chuàng)建CompletableFuture實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11