用Spring Boot Admin来监控我们的微服务

329 阅读5分钟

【转载请注明出处】:blog.csdn.net/huahao1989/…

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
@SpringBootApplication
public 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

使执行器端点可访问:

@Configuration
public 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
@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}   #需要在重启后触发信息和端点更新
  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=admin
spring.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_user
spring.mail.password=smtp_password
spring.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());
      }
    });
  }

}

其他的一些配置参数和属性可以通过官方文档来了解。

欢迎关注 “后端老鸟” 公众号