详解用Spring Boot Admin来监控我们的微服务
1.概述
SpringBootAdmin是一个Web应用程序,用于管理和监视SpringBoot应用程序。每个应用程序都被视为客户端,并注册到管理服务器。底层能力是由SpringBootActuator端点提供的。
在本文中,我们将介绍配置SpringBootAdmin服务器的步骤以及应用程序如何集成客户端。
2.管理服务器配置
由于SpringBootAdminServer可以作为servlet或webflux应用程序运行,根据需要,选择一种并添加相应的SpringBootStarter。在此示例中,我们使用ServletWebStarter。
首先,创建一个简单的SpringBootWeb应用程序,并添加以下Maven依赖项:
de.codecentric spring-boot-admin-starter-server 2.2.3 org.springframework.boot spring-boot-starter-web
之后,@EnableAdminServer将可用,因此我们将其添加到主类中,如下例所示:
@EnableAdminServer @SpringBootApplication publicclassSpringBootAdminServerApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(SpringBootAdminServerApplication.class,args); } }
至此,服务端就配置完了。
3.设置客户端
要在SpringBootAdminServer服务器上注册应用程序,可以包括SpringBootAdmin客户端或使用SpringCloudDiscovery(例如Eureka,Consul等)。
下面的例子使用SpringBootAdmin客户端进行注册,为了保护端点,还需要添加spring-boot-starter-security,添加以下Maven依赖项:
de.codecentric spring-boot-admin-starter-client 2.2.3 org.springframework.boot spring-boot-starter-security
接下来,我们需要配置客户端说明管理服务器的URL。为此,只需添加以下属性:
spring.boot.admin.client.url=http://localhost:8080
从SpringBoot2开始,默认情况下不公开运行状况和信息以外的端点,对于生产环境,应该仔细选择要公开的端点。
management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always
使执行器端点可访问:
@Configuration publicstaticclassSecurityPermitAllConfigextendsWebSecurityConfigurerAdapter{ @Override protectedvoidconfigure(HttpSecurityhttp)throwsException{ http.authorizeRequests().anyRequest().permitAll() .and().csrf().disable(); } }
为了简洁起见,暂时禁用安全性。
如果项目中已经使用了SpringCloudDiscovery,则不需要SpringBootAdmin客户端。只需将DiscoveryClient添加到SpringBootAdminServer,其余的自动配置完成。
下面使用Eureka做例子,但也支持其他SpringCloudDiscovery方案。
将spring-cloud-starter-eureka添加到依赖中:
org.springframework.cloud spring-cloud-starter-netflix-eureka-client
通过添加@EnableDiscoveryClient到配置中来启用发现
@Configuration @EnableAutoConfiguration @EnableDiscoveryClient @EnableAdminServer publicclassSpringBootAdminApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(SpringBootAdminApplication.class,args); } @Configuration publicstaticclassSecurityPermitAllConfigextendsWebSecurityConfigurerAdapter{ @Override protectedvoidconfigure(HttpSecurityhttp)throwsException{ 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.安全配置
SpringBootAdmin服务器可以访问应用程序的敏感端点,因此建议为admin服务和客户端应用程序添加一些安全配置。
由于有多种方法可以解决分布式Web应用程序中的身份验证和授权,因此SpringBootAdmin不会提供默认方法。默认情况下spring-boot-admin-server-ui提供登录页面和注销按钮。
服务器的SpringSecurity配置如下所示:
@Configuration(proxyBeanMethods=false) publicclassSecuritySecureConfigextendsWebSecurityConfigurerAdapter{ privatefinalAdminServerPropertiesadminServer; publicSecuritySecureConfig(AdminServerPropertiesadminServer){ this.adminServer=adminServer; } @Override protectedvoidconfigure(HttpSecurityhttp)throwsException{ SavedRequestAwareAuthenticationSuccessHandlersuccessHandler=newSavedRequestAwareAuthenticationSuccessHandler(); 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基本支持,这是SpringBootAdminClient注册所必需的 .csrf((csrf)->csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())//使用Cookies启用CSRF保护 .ignoringRequestMatchers( newAntPathRequestMatcher(this.adminServer.path("/instances"), HttpMethod.POST.toString()), newAntPathRequestMatcher(this.adminServer.path("/instances/*"), HttpMethod.DELETE.toString()),//禁用SpringBootAdminClient用于(注销)注册的端点的CSRF-Protection newAntPathRequestMatcher(this.adminServer.path("/actuator/**")) ))//对执行器端点禁用CSRF-Protection。 .rememberMe((rememberMe)->rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600)); } @Override protectedvoidconfigure(AuthenticationManagerBuilderauth)throwsException{ auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER"); } }
添加之后,客户端无法再向服务器注册。为了向服务器注册客户端,必须在客户端的属性文件中添加更多配置:
spring.boot.admin.client.username=admin spring.boot.admin.client.password=admin
当使用HTTPBasic身份验证保护执行器端点时,SpringBootAdminServer需要凭据才能访问它们。可以在注册应用程序时在元数据中提交凭据。在BasicAuthHttpHeaderProvider随后使用该元数据添加Authorization头信息来访问应用程序的执行端点。也可以提供自己的属性HttpHeadersProvider来更改行为(例如添加一些解密)或添加额外的请求头信息。
使用SpringBootAdmin客户端提交凭据:
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.日志文件查看器
默认情况下,日志文件无法通过执行器端点访问,因此在SpringBootAdmin中不可见。为了启用日志文件执行器端点,需要通过设置logging.file.path或将SpringBoot配置为写入日志文件logging.file.name。
SpringBootAdmin将检测所有看起来像URL的内容,并将其呈现为超链接。
还支持ANSI颜色转义。因为SpringBoot的默认格式不使用颜色,可以设置一个自定义日志格式支持颜色。
logging.file.name=/var/log/sample-boot-application.log logging.pattern.file=%clr(%d{yyyy-MM-ddHH: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添加到依赖项中:
org.springframework.boot spring-boot-starter-mail
配置一个JavaMailSender
spring.mail.username=smtp_user spring.mail.password=smtp_password spring.boot.admin.notify.mail.to=admin@example.com
无论何时注册客户端将其状态从“UP”更改为“OFFLINE”,都会将电子邮件发送到上面配置的地址。
自定义通知程序
可以通过添加实现Notifier接口的SpringBean来添加自己的通知程序,最好通过扩展AbstractEventNotifier或AbstractStatusChangeNotifier来实现。
publicclassCustomNotifierextendsAbstractEventNotifier{ privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(LoggingNotifier.class); publicCustomNotifier(InstanceRepositoryrepository){ super(repository); } @Override protectedMonodoNotify(InstanceEventevent,Instanceinstance){ returnMono.fromRunnable(()->{ if(eventinstanceofInstanceStatusChangedEvent){ LOGGER.info("Instance{}({})is{}",instance.getRegistration().getName(),event.getInstance(), ((InstanceStatusChangedEvent)event).getStatusInfo().getStatus()); } else{ LOGGER.info("Instance{}({}){}",instance.getRegistration().getName(),event.getInstance(), event.getType()); } }); } }
其他的一些配置参数和属性可以通过官方文档来了解。
到此这篇关于详解用SpringBootAdmin来监控我们的微服务的文章就介绍到这了,更多相关SpringBootAdmin监控微服务内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。