Spring Cloud 微服务(九)- 集成 Spring Boot Admin

时间:2022-07-22
本文章向大家介绍Spring Cloud 微服务(九)- 集成 Spring Boot Admin,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文简单介绍在项目中集成 spring-boot-admin

SBA(spring-boot-admin) 可简单理解为一个 UI 组件,提供 Endpoint 接口数据的界面展示。

1. 创建项目

创建 peacetrue-microservice-admin-server 项目,作为 eureka 客户端。然后添加依赖 implementation 'de.codecentric:spring-boot-admin-starter-server:2.3.0-SNAPSHOT',作为 admin 服务端。

2. 改造 Spring Security

Spring Security 默认的登陆页面如下:

Figure 1. 默认的登陆页面

参考 SBA官方文档 实现的 Reactive 版本:

WebFluxSecurityConfig

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
                                                        AdminServerProperties adminServer) {
    http.authorizeExchange(exchanges -> exchanges
            .matchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)).permitAll()
            .pathMatchers(adminServer.path("/assets/**")).permitAll()
            .pathMatchers(adminServer.path("/login")).permitAll()
            .anyExchange().authenticated()
    );
    http.formLogin()
            .loginPage(adminServer.path("/login"))
            .authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler(adminServer.path("/")));
    http.logout().logoutUrl(adminServer.path("/logout"));
    http.httpBasic(withDefaults());
    http.csrf().csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse())
            .requireCsrfProtectionMatcher(new AndServerWebExchangeMatcher(
                    CsrfWebFilter.DEFAULT_CSRF_MATCHER,
                    new NegatedServerWebExchangeMatcher(EndpointRequest.toAnyEndpoint()),
                    new NegatedServerWebExchangeMatcher(ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, adminServer.path("/instances"))),
                    new NegatedServerWebExchangeMatcher(ServerWebExchangeMatchers.pathMatchers(HttpMethod.DELETE, adminServer.path("/instances/*"))),
                    new NegatedServerWebExchangeMatcher(ServerWebExchangeMatchers.pathMatchers(adminServer.path("/actuator/*")))
            ));
    return http.build();
}

改造后,SBA 的登陆页面如下:

Figure 2. SBA登陆页面

登陆后会提示 CSRF Token has been associated to this client,原因是 CsrfWebFilter 配合 CookieServerCsrfTokenRepository 设置 Cookie 存在 BUG [1]。

忽略登陆的 CSRF 拦截后,可以正常登陆,但还是有其他功能受影响,所以直接禁用 CSRF:http.csrf().disable();

3. 效果展示

Figure 3. 应用墙

Figure 4. 应用列表

Figure 5. 内存使用情况

Figure 6. 修改日志级别

修改日志级别这个功能很好用。


1. https://github.com/spring-projects/spring-security/issues/5766