【转载请注明出处】: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@SpringBootApplicationpublic 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
使执行器端点可拜访:
@Configurationpublic 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@EnableAdminServerpublic 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=adminspring.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_userspring.mail.password=smtp_passwordspring.boot.admin.notify.mail.to=admin@example.com
无论何时注册客户端将其状态从“ 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技术、搜寻技术、爬虫技术、举荐技术、音视频互动直播等,只有有工夫我就会整顿分享,敬请期待,现成的笔记、脑图和学习材料如果大家有需要也能够公众号留言提前获取。因为自己在所有团队中根本都处于攻坚和探路的角色,搞过的货色多,遇到的坑多,解决的问题也很多,欢送大家加公众号进群一起交流学习。
【转载请注明出处】:https://blog.csdn.net/huahao1989/article/details/108039738