Spring Boot Admin 使用指南

更新于 2025-12-30

baeldung 2024-01-08

Spring Boot Admin 使用指南

1. 概述

Spring Boot Admin 是一个用于管理和监控 Spring Boot 应用程序的 Web 应用。每个被监控的应用程序被视为客户端,并向 Admin 服务器注册。其背后的核心机制依赖于 Spring Boot Actuator 提供的端点(endpoints)。

在本文中,我们将介绍如何配置 Spring Boot Admin 服务器,以及如何将应用程序注册为客户端。


2. Admin 服务器设置

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

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

添加依赖后,@EnableAdminServer 注解即可使用。我们将其添加到主类中,如下所示:

@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminServerApplication {

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

此时,我们已经可以启动 Admin 服务器,并开始注册客户端应用了。


3. 客户端设置

在 Admin 服务器搭建完成后,我们可以将第一个 Spring Boot 应用注册为客户端。为此,需添加以下 Maven 依赖:

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

接下来,需要在客户端配置文件中指定 Admin 服务器的地址:

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

注意:从 Spring Boot 2 开始,默认只暴露 healthinfo 端点。

因此,为了使 Admin 服务器能够获取更多监控信息,建议暴露所有端点:

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

4. 安全配置

由于 Spring Boot Admin 服务器会访问客户端应用的敏感端点,建议对 Admin 服务器和客户端都进行安全配置。

4.1 Admin 服务器安全配置

首先,在 Admin 服务器中添加以下 Maven 依赖:

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

这将启用安全认证,并为 Admin 应用添加登录界面(请确保使用最新版本的 Admin 组件)。

然后,添加如下安全配置类:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    private final AdminServerProperties adminServer;

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

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminServer.getContextPath() + "/");

        http.authorizeHttpRequests(req -> req
                .requestMatchers(this.adminServer.getContextPath() + "/assets/**").permitAll()
                .requestMatchers(this.adminServer.getContextPath() + "/login").permitAll()
                .anyRequest().authenticated())
            .formLogin(formLogin -> formLogin
                .loginPage(this.adminServer.getContextPath() + "/login")
                .successHandler(successHandler))
            .logout(logout -> logout.logoutUrl(this.adminServer.getContextPath() + "/logout"))
            .httpBasic(Customizer.withDefaults())
            .csrf(csrf -> 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/**")))
            .rememberMe(rememberMe -> rememberMe
                .key(UUID.randomUUID().toString())
                .tokenValiditySeconds(1209600));
        return http.build();
    }
}

添加上述安全配置后,我们会发现客户端无法再注册到服务器。

4.2 客户端注册到受保护的 Admin 服务器

为了让客户端成功注册,需在客户端的配置文件中添加以下凭据:

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

4.3 客户端自身也启用安全保护

在生产环境中,被监控的应用通常也会启用安全保护。此时,Admin 服务器将无法访问客户端的 Actuator 端点。

为解决此问题,需在客户端配置中提供元数据,以便 Admin 服务器使用正确的凭据进行访问:

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

此外,Spring Boot Admin 还支持以下高级功能:

  • JMX Bean 管理:通过集成 Jolokia 实现。
  • 日志级别动态调整:可在 UI 中实时修改日志级别。

5.1 集群支持(Hazelcast)

Spring Boot Admin 支持通过 Hazelcast 实现集群节点间的状态同步。只需添加以下依赖:

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

Hazelcast 将通过自动配置生效。

若需持久化或自定义 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. 通知功能

Spring Boot Admin 支持在客户端状态发生变化时发送通知。支持的通知方式包括:

  • Email(电子邮件)
  • PagerDuty
  • OpsGenie
  • Hipchat
  • Slack
  • Let’s Chat

6.1 电子邮件通知

要启用邮件通知,首先添加 Spring Boot Mail 依赖:

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

然后在配置文件中设置 SMTP 信息:

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 自定义通知配置

Spring Boot Admin 还支持高度自定义的通知逻辑。例如:

  • 使用 提醒通知器(Reminding Notifier):在问题未解决前定期重复发送通知。
  • 使用 过滤通知器(Filtering Notifier):仅向特定客户端发送通知。

示例配置如下:

@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 应用的基本步骤。

得益于 Spring Boot 的自动配置机制,我们只需进行少量配置,即可快速搭建一个功能完整的 Admin 服务器,实现对多个微服务应用的集中监控与管理。