关于springboot:用Spring-Boot-Admin来监控我们的微服务

4次阅读

共计 7517 个字符,预计需要花费 19 分钟才能阅读完成。

【转载请注明出处】: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
@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());
      }
    });
  }

}

其余的一些配置参数和属性能够通过官网文档来理解。

欢送关注“后端老鸟”公众号,接下来会发一系列的专题文章,包含 Java、Python、Linux、SpringBoot、SpringCloud、Dubbo、算法、技术团队的治理等,还有各种脑图和学习材料,NFC 技术、搜寻技术、爬虫技术、举荐技术、音视频互动直播等,只有有工夫我就会整顿分享,敬请期待,现成的笔记、脑图和学习材料如果大家有需要也能够公众号留言提前获取。因为自己在所有团队中根本都处于攻坚和探路的角色,搞过的货色多,遇到的坑多,解决的问题也很多,欢送大家加公众号进群一起交流学习。

【转载请注明出处】:https://blog.csdn.net/huahao1989/article/details/108039738

正文完
 0