Spring Boot Admin指南2.4.1

原文地址:https://www.baeldung.com/spring-boot-admin

目录

1.概述

2. 管理服务器设置

3. 设置客户端

4.安全配置

5. 监控管理功能

6. 通知

6.1电子邮件通知

6.2. Hipchat 通知

6.3. 自定义通知配置

7. 结论


1.概述

Spring Boot Admin是一个 Web 应用程序,用于管理和监控 Spring Boot 应用程序。每个应用程序都被视为客户端并注册到管理服务器。在幕后,Spring Boot Actuator 端点赋予了魔力。

在本文中,我们将描述配置 Spring Boot 管理服务器的步骤以及应用程序如何成为客户端。

2. 管理服务器设置


首先,我们需要创建一个简单的 Spring Boot Web 应用程序并添加以下Maven 依赖项:

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.4.1</version>
</dependency>


在此之后,@EnableAdminServer将可用,因此我们将其添加到主类中,如下例所示:

@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminServerApplication(exclude = AdminServerHazelcastAutoConfiguration.class) {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootAdminServerApplication.class, args);
    }
}


此时,我们已准备好启动服务器并注册客户端应用程序。

3. 设置客户端


现在,在我们设置好管理服务器之后,我们可以将我们的第一个 Spring Boot 应用程序注册为客户端。我们必须添加以下Maven 依赖项:

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


接下来,我们需要配置客户端以了解管理服务器的基本 URL。为此,我们只需添加以下属性:

spring.boot.admin.client.url=http://localhost:8080
从 Spring Boot 2 开始,除了health和info之外的端点默认不公开。

让我们公开所有端点:

management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always


4.安全配置


Spring Boot 管理服务器可以访问应用程序的敏感端点,因此建议我们为管理和客户端应用程序添加一些安全配置。

首先,我们将专注于配置管理服务器的安全性。我们必须添加以下Maven 依赖项:

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-server-ui-login</artifactId>
    <version>1.5.7</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.4.0</version>
</dependency>


这将启用安全性并向管理应用程序添加登录界面。

接下来,我们将添加一个安全配置类,如下所示:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final AdminServerProperties adminServer;

    public WebSecurityConfig(AdminServerProperties adminServer) {
        this.adminServer = adminServer;
    }

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

        http
            .authorizeRequests()
                .antMatchers(this.adminServer.getContextPath() + "/assets/**").permitAll()
                .antMatchers(this.adminServer.getContextPath() + "/login").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage(this.adminServer.getContextPath() + "/login")
                .successHandler(successHandler)
                .and()
            .logout()
                .logoutUrl(this.adminServer.getContextPath() + "/logout")
                .and()
            .httpBasic()
                .and()
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringRequestMatchers(
                  new AntPathRequestMatcher(this.adminServer.getContextPath() +
                    "/instances", HttpMethod.POST.toString()),
                  new AntPathRequestMatcher(this.adminServer.getContextPath() +
                    "/instances/*", HttpMethod.DELETE.toString()),
                  new AntPathRequestMatcher(this.adminServer.getContextPath() + "/actuator/**"))
                .and()
            .rememberMe()
                .key(UUID.randomUUID().toString())
                .tokenValiditySeconds(1209600);
    }
}


有一个简单的安全配置,但添加后,我们会注意到客户端无法再注册到服务器。

为了将客户端注册到新安全的服务器,我们必须在客户端的属性文件中添加更多配置:

spring.boot.admin.client.username=admin
spring.boot.admin.client.password=admin


我们已经到了保护我们的管理服务器的地方。在生产系统中,我们试图监控的应用程序自然会受到保护。因此,我们还将为客户端添加安全性——我们会在管理服务器的 UI 界面中注意到客户端信息不再可用。

我们必须添加一些我们将发送到管理服务器的元数据。服务器使用此信息连接到客户端的端点:

spring.security.user.name=client
spring.security.user.password=client
spring.boot.admin.client.instance.metadata.user.name=${spring.security.user.name}
spring.boot.admin.client.instance.metadata.user.password=${spring.security.user.password}


当然,通过 HTTP 发送凭据并不安全——因此通信需要通过 HTTPS。

5. 监控管理功能


Spring Boot Admin 可以配置为仅显示我们认为有用的信息。我们只需要更改默认配置并添加我们自己需要的指标:

spring.boot.admin.routes.endpoints=env, metrics, trace, jolokia, info, configprops
随着我们进一步深入,我们将看到还有一些其他的功能可以探索。我们正在谈论使用Jolokia的JMX bean 管理以及Loglevel管理。

Spring Boot Admin 还支持使用 Hazelcast 进行集群复制。我们只需要添加以下Maven 依赖项,然后让自动配置完成剩下的工作:

<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast</artifactId>
    <version>4.0.3</version>
</dependency>


如果我们想要一个持久化的 Hazelcast 实例,我们将使用自定义配置:
 

@Configuration
public class HazelcastConfig {

    @Bean
    public Config hazelcast() {
        MapConfig eventStoreMap = new MapConfig("spring-boot-admin-event-store")
          .setInMemoryFormat(InMemoryFormat.OBJECT)
          .setBackupCount(1)
          .setEvictionConfig(new EvictionConfig().setEvictionPolicy(EvictionPolicy.NONE))
          .setMergePolicyConfig(new MergePolicyConfig(PutIfAbsentMergePolicy.class.getName(), 100));

        MapConfig sentNotificationsMap = new MapConfig("spring-boot-admin-application-store")
          .setInMemoryFormat(InMemoryFormat.OBJECT)
          .setBackupCount(1)
          .setEvictionConfig(new EvictionConfig().setEvictionPolicy(EvictionPolicy.LRU))
          .setMergePolicyConfig(new MergePolicyConfig(PutIfAbsentMergePolicy.class.getName(), 100));

        Config config = new Config();
        config.addMapConfig(eventStoreMap);
        config.addMapConfig(sentNotificationsMap);
        config.setProperty("hazelcast.jmx", "true");

        config.getNetworkConfig()
          .getJoin()
          .getMulticastConfig()
          .setEnabled(false);
        TcpIpConfig tcpIpConfig = config.getNetworkConfig()
          .getJoin()
          .getTcpIpConfig();
        tcpIpConfig.setEnabled(true);
        tcpIpConfig.setMembers(Collections.singletonList("127.0.0.1"));
        return config;
    }
}


6. 通知


接下来,让我们讨论一下如果我们的注册客户端发生问题时从管理服务器接收通知的可能性。以下通知器可用于配置:

  • 电子邮件
  • 寻呼机
  • 行动精灵
  • Hipchat
  • 松弛
  • 让我们聊天


6.1电子邮件通知


我们将首先专注于为我们的管理服务器配置邮件通知。为此,我们必须添加邮件启动器依赖项,如下所示:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.4.0</version>
</dependency>


在此之后,我们必须添加一些邮件配置:

spring.mail.host=smtp.example.com
spring.mail.username=smtp_user
spring.mail.password=smtp_password
spring.boot.admin.notify.mail.to=admin@example.com


现在,每当我们的注册客户将其状态从 UP 更改为 OFFLINE 或其他情况时,都会向上面配置的地址发送一封电子邮件。对于其他通知器,配置类似。

6.2. Hipchat 通知


正如我们将看到的,与 Hipchat 的集成非常简单。只需设置几个强制属性:

spring.boot.admin.notify.hipchat.auth-token=<generated_token>
spring.boot.admin.notify.hipchat.room-id=<room-id>
spring.boot.admin.notify.hipchat.url=https://yourcompany.hipchat.com/v2/


定义好这些后,我们会在 Hipchat 聊天室中注意到,只要客户端状态发生变化,我们就会收到通知。

6.3. 自定义通知配置


我们可以配置一个自定义通知系统,并为此提供一些强大的工具。我们可以使用提醒通知器发送预定通知,直到客户端状态发生变化。

或者,也许我们想向一组过滤的客户端发送通知。为此,我们可以使用过滤通知器:

@Configuration
public class NotifierConfiguration {
    private final InstanceRepository repository;
    private final ObjectProvider<List<Notifier>> otherNotifiers;

    public NotifierConfiguration(InstanceRepository repository,
      ObjectProvider<List<Notifier>> otherNotifiers) {
        this.repository = repository;
        this.otherNotifiers = otherNotifiers;
    }

    @Bean
    public FilteringNotifier filteringNotifier() {
        CompositeNotifier delegate =
          new CompositeNotifier(this.otherNotifiers.getIfAvailable(Collections::emptyList));
        return new FilteringNotifier(delegate, this.repository);
    }

    @Bean
    public LoggingNotifier notifier() {
        return new LoggingNotifier(repository);
    }

    @Primary
    @Bean(initMethod = "start", destroyMethod = "stop")
    public RemindingNotifier remindingNotifier() {
        RemindingNotifier remindingNotifier = new RemindingNotifier(filteringNotifier(), repository);
        remindingNotifier.setReminderPeriod(Duration.ofMinutes(5));
        remindingNotifier.setCheckReminderInverval(Duration.ofSeconds(60));
        return remindingNotifier;
    }
}


7. 结论


本介绍性教程介绍了使用 Spring Boot Admin 监视和管理他的 Spring Boot 应用程序必须执行的简单步骤。

自动配置允许我们只添加一些次要配置,并在最后拥有一个完全工作的管理服务器。

而且,与往常一样,本指南的示例代码可以在 Github 上找到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值