Spring Boot管理者ガイド

Spring Boot Adminのガイド

1. 概要

Spring Boot Adminは、SpringBootアプリケーションの管理と監視に使用されるWebアプリケーションです。 各アプリケーションはクライアントと見なされ、管理サーバーに登録されます。 舞台裏では、Spring Boot Actuatorエンドポイントによって魔法が与えられます。

この記事では、Spring Boot Adminサーバーを構成する手順と、アプリケーションがクライアントになる方法について説明します。

2. 管理サーバーのセットアップ

まず、単純なSpring Boot Webアプリケーションを作成し、次のMaven dependencyを追加する必要があります。


    de.codecentric
    spring-boot-admin-starter-server
    2.1.6

この後、@EnableAdminServerが使用可能になるため、次の例に示すように、メインクラスに追加します。

@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminServerApplication {

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

この時点で、サーバーを起動してクライアントアプリケーションを登録する準備が整いました。

3. クライアントの設定

これで、管理サーバーをセットアップした後、最初のSpringBootアプリケーションをクライアントとして登録できます。 次のMaven dependencyを追加する必要があります。


    de.codecentric
    spring-boot-admin-starter-client
    2.1.6

次に、管理サーバーのベースURLを認識するようにクライアントを構成する必要があります。 これを実現するには、次のプロパティを追加するだけです。

spring.boot.admin.client.url=http://localhost:8080

Spring Boot 2以降、healthinfo以外のエンドポイントはデフォルトで公開されません。

すべてのエンドポイントを公開しましょう。

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

4. セキュリティ構成

Spring Boot Adminサーバーはアプリケーションの機密エンドポイントにアクセスできるため、it’s advised that we add some security configuration to both admin and client application.

最初に、管理サーバーのセキュリティの構成に焦点を当てます。 次のMaven dependenciesを追加する必要があります。


    de.codecentric
    spring-boot-admin-server-ui-login
    1.5.7


    org.springframework.boot
    spring-boot-starter-security
    2.1.8.RELEASE

これにより、セキュリティが有効になり、ログインアプリケーションが管理アプリケーションに追加されます。

次に、以下に示すように、セキュリティ構成クラスを追加します。

@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

さらに進むと、探索できる他の機能がいくつかあることがわかります。 JolokiaLoglevel管理を使用したJMX bean managementについて話します。

Spring Boot Adminは、Hazelcastを使用したクラスター複製もサポートしています。 次のMaven dependencyを追加し、残りは自動構成に任せるだけです。


    com.hazelcast
    hazelcast
    3.12.2

Hazelcastの永続的なインスタンスが必要な場合は、カスタム構成を使用します。

@Configuration
public class HazelcastConfig {

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

        MapConfig sentNotificationsMap = new MapConfig("spring-boot-admin-application-store")
          .setInMemoryFormat(InMemoryFormat.OBJECT)
          .setBackupCount(1)
          .setEvictionPolicy(EvictionPolicy.LRU)
          .setMergePolicyConfig(new MergePolicyConfig(PutIfAbsentMapMergePolicy.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. 通知

次に、登録済みのクライアントで問題が発生した場合に、管理サーバーから通知を受信する可能性について説明します。 次の通知機能を構成に使用できます。

  • Eメール

  • PagerDuty

  • OpsGenie

  • ヒップチャット

  • スラック

  • チャットしよう

6.1. メール通知

まず、管理サーバーのメール通知の構成に焦点を当てます。 これを行うには、以下に示すようにmail starter dependencyを追加する必要があります。


    org.springframework.boot
    spring-boot-starter-mail
    2.1.7.RELEASE

この後、メール構成を追加する必要があります。

spring.mail.host=smtp.example.com
spring.mail.username=smtp_user
spring.mail.password=smtp_password
[email protected]

現在、登録済みのクライアントがステータスをUPからOFFLINEまたはそれ以外に変更するたびに、上記で設定したアドレスにメールが送信されます。 他の通知機能については、構成は同様です。

6.2. Hipchat通知

後で説明するように、Hipchatとの統合は非常に簡単です。設定する必須のプロパティはごくわずかです。

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

これらを定義すると、Hipchatルームで、クライアントのステータスが変更されるたびに通知を受け取ることがわかります。

6.3. カスタマイズされた通知構成

このための強力なツールを自由に使用できるカスタム通知システムを構成できます。 reminding notifierを使用して、クライアントのステータスが変更されるまでスケジュールされた通知を送信できます。

または、フィルター処理されたクライアントのセットに通知を送信することもできます。 このために、filtering notifier:を使用できます

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

    public NotifierConfiguration(InstanceRepository repository,
      ObjectProvider> 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アプリケーションを監視および管理するために必要な簡単な手順について説明します。

自動構成により、一部のマイナー構成のみを追加し、最後に完全に機能する管理サーバーを追加できます。

そして、いつものように、このガイドのサンプルコードはover on Githubにあります。