SpringCloud集成Spring Boot Admin实现服务管理与监控

x33g5p2x  于2022-04-14 转载在 Spring  
字(5.3k)|赞(0)|评价(0)|浏览(382)

SpringCloud集成Spring Boot Admin 用于管理和监控各个springboot应用

官网https://codecentric.github.io/spring-boot-admin/current/

官网给我提供了两种使用方式

1. 使用Spring Boot Admin Client

1.1、搭建Spring Boot Admin Server

  1. 新建一个springboot项目
  2. 引入依赖
  3. 创建启动类
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.4.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
server:
	port: 8080
spring:
	application:
		name: spring-boot-admin
// 注意: 这里不需要@SpringBootApplication
@Configuration
@EnableAutoConfiguration
@EnableAdminServer
public class SpringBootAdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAdminApplication.class, args);
    }
}

1.2、搭建客户端,注册到Admin服务端

再创建一个springboot应用

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>2.4.0-SNAPSHOT</version>
</dependency>

<!--为什么要引入security,后面会讲到-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
# 指定admin server的地址
spring.boot.admin.client.url= http://localhost:8080  
# 暴露端点
management.endpoints.web.exposure.include=*

注意

  1. 我们为了方便测试,为简洁起见,现在禁用安全性
@Configuration
public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll()  
            .and().csrf().disable();
    }
}

这样我们在访问 http://localhost:8080 时 不需要登录

  1. 但是在生产环境,为了安全起见,还有另一种配置方式
    由于在分布式 Web 应用程序中有多种解决身份验证和授权的方法,因此 Spring Boot Admin 没有提供默认方法。默认情况下spring-boot-admin-server-ui提供登录页面和注销按钮。

服务器的 Spring Security 配置可能如下所示:

@Configuration(proxyBeanMethods = false)
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

    private final AdminServerProperties adminServer;

    private final SecurityProperties security;

    public SecuritySecureConfig(AdminServerProperties adminServer, SecurityProperties security) {
        this.adminServer = adminServer;
        this.security = security;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminServer.path("/"));

        http.authorizeRequests(
                (authorizeRequests) -> authorizeRequests.antMatchers(adminServer.path("/assets/**")).permitAll()  // 授予对所有静态资产和登录页面的公共访问权限。
                        .antMatchers(adminServer.path("/actuator/info")).permitAll()
                        .antMatchers(adminServer.path("/actuator/health")).permitAll()
                        .antMatchers(adminServer.path("/login")).permitAll().anyRequest().authenticated()   //必须对所有其他请求进行身份验证。
        ).formLogin(
                (formLogin) -> formLogin.loginPage(adminServer.path("/login")).successHandler(successHandler).and()    //配置登录和注销。
        ).logout((logout) -> logout.logoutUrl(adminServer.path("/logout"))).httpBasic(Customizer.withDefaults())    //启用 HTTP 基本支持。这是 Spring Boot Admin Client 注册所必需的。
                .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())         //使用 Cookie 启用 CSRF 保护
                        .ignoringRequestMatchers(
                                new AntPathRequestMatcher(adminServer.path("/instances"),
                                        HttpMethod.POST.toString()),
                                new AntPathRequestMatcher(adminServer.path("/instances/*"),      // 为 Spring Boot Admin Client 用于(取消)注册的端点禁用 CSRF 保护。
                                        HttpMethod.DELETE.toString()),
                                new AntPathRequestMatcher(adminServer.path("/actuator/**"))     //	禁用执行器端点的 CSRF 保护。
                        ))
                .rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
    }

    // Required to provide UserDetailsService for "remember functionality"
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser(security.getUser().getName())
                .password("{noop}" + security.getUser().getPassword()).roles("USER");
    }

}

同时在客户端 添加配置

spring.boot.admin.client:
   username: admin
   password: 123456

2. 使用注册中心(eureka、consul、nacos)

这里可以通过注册中心进行服务发现,不再需要进行手动注册到admin server

<dependency>
     <groupId>com.alibaba.cloud</groupId>
     <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
 </dependency>

启动类

@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();
        }
    }
}

如果希望加入登录授权的话,配置方式同上面一样

server:
  port: 8769

spring:
  application:
    name: ERC-MONITOR
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYS

在client,我们只需要引入健康检查,开启暴露端点,即可

<!--健康检查-->
  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

这种方式在SpringCloud中使用比较简洁,减少了client的配置(推荐使用)

相关文章