Spring Boot Admin 1.5.7

1.什么是Spring Boot Admin

codecentric的Spring Boot Admin是一个社区项目,用于管理和监控SpringBoot®应用程序。 应用程序向我们的Spring Boot Admin Client注册(通过HTTP)或使用SpringCloud®(例如Eureka,Consul)发现。 UI只是Spring Boot Actuator端点上的AngularJs应用程序。

2.入门

2.1 设置Spring Boot Admin Server

首先,您需要设置您的服务器。 要做到这一点,只需设置一个简单的启动项目。

1.将Spring Boot Admin Server启动器添加到您的依赖项:

pom.xml

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

2.通过将@EnableAdminServer添加到您的配置来引入Spring Boot Admin Server配置:

@Configuration
@EnableAutoConfiguration
@EnableAdminServer
public class SpringBootAdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAdminApplication.class, args);
    }
}

https://github.com/codecentric/spring-boot-admin/blob/1.5.x/spring-boot-admin-samples

2.2 注册客户端应用程序

要在SBA服务器上注册您的应用程序,您可以包含SBA客户端或使用Spring Cloud Discovery(例如Eureka,Consul,...)。 在SBA服务器端使用静态配置还有一个简单的选项。

2.2.1  Spring Boot Admin客户端

每个要注册的应用程序都必须包含Spring Boot Admin Client。

1.将spring-boot-admin-starter-client添加到依赖项中:

pom.xml

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

2.通过配置Spring Boot Admin Server的URL来启用SBA客户端:

application.yml

spring.boot.admin.url: http://localhost:8080    <1>
management.security.enabled: false     <2>

<1> 要注册的Spring Boot Admin Server的URL。
<2> 从Spring Boot 1.5.x开始,默认情况下所有端点都是安全的。 为简洁起见,我们暂时禁用了安全性。 查看有关如何处理安全端点的安全性部分。

2.2.2. Spring Cloud Discovery

如果您已经为应用程序使用Spring Cloud Discovery,则不需要SBA客户端。 只需将Spring Boot Admin Server设置为DiscoveryClient,其余部分由我们的AutoConfiguration完成。

以下步骤适用于使用Eureka,但也支持其他Spring Cloud Discovery实施

3.客户端应用

3.1 在应用程序列表中显示版本

要让版本显示在应用程序列表中,您可以使用spring-boot-maven-plugin中的build-info目标,该目标生成META-INF/build-info.properties

pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>build-info</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

3.2 JMX-bean管理

要在管理UI中与JMX-beans交互,您必须在应用程序中包含Jolokia。 如果您使用的是spring-boot-admin-starter-client,它将会为您提供,不需要再次引入Jolokia:

pom.xml

<dependency>
    <groupId>org.jolokia</groupId>
    <artifactId>jolokia-core</artifactId>
</dependency>

3.3 日志级别管理 

对于使用Spring Boot 1.5.x(或更高版本)的应用程序,您可以开箱即用地管理日志级别。 对于使用旧版Spring Boot的应用程序,日志级别管理仅适用于Logback。 它可以通过JMX访问,因此在您的应用程序中包含Jolokia。 此外,您还配置了Logback的JMXConfigurator:

logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <include resource="org/springframework/boot/logging/logback/base.xml"/>
  <jmxConfigurator/>
</configuration>

注意:

如果要将多个应用程序部署到同一个JVM并且存在多个Logback-JMX-bean,则UI将选择JMXConfigurator,其context-name等于您的应用程序名称。 在这种情况下,您需要在logback-configuration中设置contextName。

3.4. Spring Boot Admin Client

Spring Boot Admin Client在管理服务器上注册应用程序。 这是通过定期向SBA服务器发送HTTP post请求来提供有关应用程序的信息来完成的。 它还将Jolokia添加到您的应用程序中,以便可以通过HTTP访问JMX-beans。

Table 1. Spring Boot Admin Client configuration options
Property name Description Default value

spring.boot.admin.client.enabled

启用Spring Boot Admin Client。

true

spring.boot.admin.url

逗号分隔Spring Boot Admin服务器的有序URL列表以进行注册。 这会触发自动配置。强制性.

 

spring.boot.admin.api-path

管理服务器上的注册端点的Http路径。

"api/applications"

spring.boot.admin.username
spring.boot.admin.password

用户名和密码,以防SBA服务器api受到HTTP基本身份验证的保护。

 

spring.boot.admin.period

重复注册的间隔(在ms中)。

10,000

spring.boot.admin.connect-timeout

连接注册超时(在ms中)。

5,000

spring.boot.admin.read-timeout

读取注册超时(以ms为单位)。

5,000

spring.boot.admin.auto-registration

如果将注册应用程序的周期任务设置为true,则在应用程序就绪后将自动调度注册应用程序。

true

spring.boot.admin.auto-deregistration

当上下文关闭时,切换到在Spring引导管理服务器上启用自动撤销注册。

false

spring.boot.admin.register-once

如果设置为true,客户端将只对一个管理服务器进行注册(按照spring.boot.admin.url定义的顺序);如果管理服务器宕机,将自动注册到下一个管理服务器。如果为false,将对所有管理服务器进行注册。

true

spring.boot.admin.client.health-url

要注册的客户机-健康url。在可到达URL不同的情况下(例如Docker)可以被重写。在注册表中必须是唯一的。

Guessed based on management-url and endpoints.health.id.

spring.boot.admin.client.management-base-url

用于计算要注册的management-url的基本URL。 路径在运行时推断,并附加到基本URL。

Guessed based on management.port, service-url and server.servlet-path.

spring.boot.admin.client.management-url

Management-url to register with. Can be overridden in case the reachable url is different (e.g. Docker).

Guessed based on management-base-url and management.context-path.

spring.boot.admin.client.service-base-url

Base url for computing the service-url to register with. The path is inferred at runtime, and appended to the base url.

Guessed based on hostname, server.port.

spring.boot.admin.client.service-url

Client-service-url to register with. Can be overridden in case the reachable url is different (e.g. Docker).

Guessed based on service-base-url and server.context-path.

spring.boot.admin.client.name

Name to register with.

${spring.application.name} if set, "spring-boot-application"otherwise.

spring.boot.admin.client.prefer-ip

Use the ip-address rather then the hostname in the guessed urls. If server.address / management.address is set, it get used. Otherwise the IP address returned from InetAddress.getLocalHost() gets used.

false

spring.boot.admin.client.metadata.*

Metadata key-value-pairs to be associated with this instance.

 
Table 2. Instance metadata options
Key Value Default value

user.name
user.password

用于访问端点的凭据。

 

4.Spring Boot Admin Server

表3. Spring Boot Admin Server配置选项
Property name Description Default value

spring.boot.admin.context-path

context-path是应该为Admin Server静态资产和API提供服务的路径的前缀。 相对于Dispatcher-Servlet。

 

spring.boot.admin.monitor.period

以ms为单位的时间间隔,用于更新状态信息过期的应用程序的状态.

10,000

spring.boot.admin.monitor.status-lifetime

应用程序状态的生命周期,以ms为单位。 在生命周期到期之前,不会查询应用程序 /health-endpoint

10,000

spring.boot.admin.monitor.connect-timeout

查询应用程序的状态和信息时,以毫秒为单位连接超时。

2,000

spring.boot.admin.monitor.read-timeout

查询应用程序的状态和信息时,以毫秒为单位读取超时。

5,000

spring.boot.admin.routes.endpoints

可以通过spring boot admin zuul proxy获得的enpoints。 如果使用其他端点编写ui模块,则需要添加它们。

"env", "metrics", "trace", "dump", "jolokia", "info", "configprops", "activiti", "logfile", "refresh", "flyway", "liquibase", "loggers"

spring.boot.admin.metadata-keys-to-sanitize

匹配这些正则表达式模式的键的元数据值将在所有json输出中清除。

".password$", ".*secret$", ".*key$", ".$token$", ".credentials.", ".*vcap_services$"

4.1. Spring Cloud Discovery

Spring Boot Admin Server可以使用Spring Clouds DiscoveryClient来发现应用程序。 优点是客户端不必包含spring-boot-admin-starter-client。 您只需将DiscoveryClient实现添加到管理服务器 - 其他一切都由AutoConfiguration完成。

4.4.1SimpleDiscoveryClient配置

Spring Boot Admin包含SimpleDiscoveryClient。 这允许您通过配置指定客户端应用程序,而无需将SBA客户端或DiscoveryClient实现添加到受监视的应用程序:

application.yml

spring:
  cloud:
    discovery:
      client:
        simple:
          instances:
            test:
              - uri: http://instance1.intern:8080
                metadata:
                  management.context-path: /actuator
              - uri: http://instance2.intern:8080
                metadata:
                  management.context-path: /actuator

4.1.2  其他DiscoveryClient实现(Eureka,Zookeeper,Consul,...)

Spring Boot Admin支持Spring Cloud的DiscoveryClient的所有其他实现。 您需要将其添加到Spring Boot Admin Server并正确配置它。

4.1.3 将ServiceInstances转换为受监视的应用程序

服务注册表中的信息由ServiceInstanceConverter转换。 Spring Boot Admin附带默认和Eureka转换器实现。 AutoConfiguration选择正确的一个。

注意:

您可以使用SBA服务器配置选项和实例元数据修改注册表中的信息如何用于注册应用程序。 元数据中的值优先于服务器配置。 如果有很多选项不符合您的需求,您可以提供自己的ServiceInstanceConverter。

注意:

使用Eureka时,Eureka已知的healthCheckUrl用于健康检查,可以使用eureka.instance.healthCheckUrl在您的客户端上进行设置。

表4 实例元数据选项

 
Key Value Default value

user.name
user.password

用于访问端点的凭据。

 

management.port

端口在服务URL中替换,并将用于访问执行器端点。

 

management.context-path

该路径附加到服务URL,并将用于访问执行器端点。

${spring.boot.admin.discovery.converter.mangement-context-path}

health.path

该路径将附加到服务URL,并将用于运行状况检查。 被EurekaServiceInstanceConverter忽略。

${spring.boot.admin.discovery.converter.health-endpoint}

Table 5. 发现配置选项
Property name Description Default value

spring.boot.admin.discovery.enabled

为管理服务器启用DiscoveryClient支持。

true

spring.boot.admin.discovery.converter.management-context-path

当DefaultServiceInstanceConverter转换management-url时,将附加到已发现服务的service-url。

 

spring.boot.admin.discovery.converter.health-endpoint-path

当DefaultServiceInstanceConverter转换health-url时,将附加到已发现服务的management-url。

"health"

spring.boot.admin.discovery.ignored-services

使用发现而未注册为应用程序时,将忽略此服务。 支持简单模式(例如“foo *”,“bar”,“foo * bar”)。

 

spring.boot.admin.discovery.services

使用发现并注册为应用程序时将包含此服务。 支持简单模式(例如“foo *”,“bar”,“foo * bar”)。

"*"

4.2集群

Spring Boot Admin Server通过Hazelcast支持群集复制。 当存在HazelcastConfig-或HazelcastInstance-Bean时,它会自动启用。 您还可以将Hazelcast实例配置为持久性,以保持状态重新启动。

1.将Hazelcast添加到您的依赖项:

pom.xml

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

2.实例化HazelcastConfig:

@Configuration
@EnableAutoConfiguration
@EnableAdminServer
public class SpringBootAdminApplication {
  @Bean
  public Config hazelcastConfig() {
    return new Config().setProperty("hazelcast.jmx", "true")
        .addMapConfig(new MapConfig("spring-boot-admin-application-store").setBackupCount(1)
            .setEvictionPolicy(EvictionPolicy.NONE))
        .addListConfig(new ListConfig("spring-boot-admin-event-store").setBackupCount(1)
            .setMaxSize(1000));
  }

  public static void main(String[] args) {
    SpringApplication.run(SpringBootAdminApplication.class, args);
  }
}
表6. Hazelcast配置选项
Property name Description Default value

spring.boot.admin.hazelcast.enabled

Enables the Hazelcast support

true

spring.boot.admin.hazelcast.application-store

Name of the Hazelcast-map to store the applications

"spring-boot-admin-application-store"

spring.boot.admin.hazelcast.event-store

Name of the Hazelcast-list to store the events

"spring-boot-admin-event-store"

4.3. Notifications[通知]


  提醒通知

提醒通知程序为down/offline (宕机/离线)应用程序发送提醒,它将通知的发送委托给另一个通知程序

默认情况下,当注册的应用程序更改为DOWN或OFFLINE时会触发提醒。 您可以通过setReminderStatuses()更改此行为。 当状态变为非触发状态或关注时,提醒结束应用程序被取消注册。

默认情况下,提醒每10分钟发送一次,以更改此用途setReminderPeriod()。 提醒通知程序本身不会启动后台线程来发送提醒,您需要注意这一点,如下面的给出示例所示;

如何配置提醒

@Configuration
@EnableScheduling
public class NotifierConfiguration {
    @Autowired
    private Notifier notifier;
@Bean
@Primary
public RemindingNotifier remindingNotifier() {
    RemindingNotifier remindingNotifier = new RemindingNotifier(notifier);
    remindingNotifier.setReminderPeriod(TimeUnit.MINUTES.toMillis(5));   1
    return remindingNotifier;
}
@Scheduled(fixedRate = 60_000L)   2
public void remind() {
    remindingNotifier().sendReminders();
    }
  }

1 提醒将每5分钟发送一次。

2 计划每60秒发送一次适当的提醒

4.3.1. Filtering notifications

FilteringNotifier允许您根据可在运行时add/remove的规则筛选某些通知。 它将通知的发送委托给另一个通知程序。

如果向ApplicationContext添加FilteringNotifier,则api / notifications / filter上的RESTful接口可用。 发生这种情况时,ui会显示管理过滤器的选项。

如果您不希望在部署应用程序时收到通知,则此通知程序非常有用。 在停止应用程序之前,您可以通过POST请求或ui添加(过期)过滤器。

如何配置过滤

@Configuration
@EnableScheduling
public class NotifierConfiguration {  1
  @Autowired
  private Notifier delegate;

  @Bean
  public FilteringNotifier filteringNotifier() { 
    return new FilteringNotifier(delegate);
  }

  @Bean
  @Primary
  public RemindingNotifier remindingNotifier() { 
    RemindingNotifier notifier = new RemindingNotifier(filteringNotifier());
    notifier.setReminderPeriod(TimeUnit.SECONDS.toMillis(10));
    return notifier;
  }

  @Scheduled(fixedRate = 1_000L)  2
  public void remind() {
    remindingNotifier().sendReminders();
  }
}

1 使用委托添加FilteringNotifier bean(例如,配置时为MailNotifier)
2 使用FilteringNotifier作为委托添加RemindingNotifier作为主bean。

此示例组合了提醒和过滤通知程序。 这允许您在部署的应用程序在一定时间内未重新启动后(直到过滤器过期)收到通知。

4.3.2.邮件通知

使用spring-boot-starter-mail配置JavaMailSender并设置收件人。

pom.xml

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

application.properties

spring.mail.host=smtp.example.com
[email protected]

表7.邮件通知配置选项

 

Property name Description Default value

spring.boot.admin.notify.mail.enabled

启用邮件通知

true

spring.boot.admin.notify.mail.ignore-changes

以逗号分隔的状态更改列表将被忽略。 格式:“<from-status>:<to-status>”。 允许使用通配符。

"UNKNOWN:UP"

spring.boot.admin.notify.mail.to

以逗号分隔的邮件收件人列表

"root@localhost"

spring.boot.admin.notify.mail.cc

以逗号分隔的抄送收件人名单

 

spring.boot.admin.notify.mail.from

邮件发件人

 

spring.boot.admin.notify.mail.subject

邮件主题。 支持SpEL表达式

"#{application.name} (#{application.id}) is #{to.status}"

spring.boot.admin.notify.mail.text

邮件正文。 支持SpEL表达式

"#{application.name} (#{application.id})\nstatus changed from #{from.status} to #{to.status}\n\n#{application.healthUrl}"

通知类型还支持具体参考官网文档http://codecentric.github.io/spring-boot-admin/1.5.7/#_notifications

4.4UI模块

除了核心UI之外,还有以下模块可以通过将jar文件添加到类路径来包含:

  • spring-boot-admin-server-ui-activiti

  • spring-boot-admin-server-ui-hystrix

  • spring-boot-admin-server-ui-turbine

4.4.1Hystrix UI模块

Hystrix模块使用hystrix-dashboard显示来自Hystrix流的指标。

1.将ui模块添加到类路径中:

pom.xml

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-server-ui-hystrix</artifactId>
    <version>1.5.7</version>
</dependency>

2.将/hystrix.stream添加到代理端点:

application.yml

spring.boot.admin.routes.endpoints: env,metrics,dump,jolokia,info,configprops,trace,logfile,refresh,flyway,liquibase,heapdump,loggers,auditevents,hystrix.stream

 4.4.2 Turbine UI模块

Turbine模块使用hystrix-dashboard显示Turbine流的指标。 UI模块不会为您配置Turbine。 您可以将Turbine作为单独的应用程序运行,也可以将其集成到Spring Boot Admin应用程序中.

1.将ui模块添加到类路径中:

pom.xml
 

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-server-ui-turbine</artifactId>
    <version>1.5.7</version>
</dependency>

2.配置Turbine服务器和集群

application.yml


spring.boot.admin.turbine:
 clusters: default
 location: turbine

spring.boot.admin.turbine.location Turbine服务器配置可以试serviceId(有注册中心的前提下)也可以是URL[默认Turbine服务器为'turbine']

Property name Description Default value
spring.boot.admin.turbine.enabled 为Turbine启用Spring Boot Admin后端配置。 true
spring.boot.admin.turbine.location Turbine服务器的ServiceId或URL(没有/turbine.stream路径)。 必须可以从管理服务器访问。 "turbine"
spring.boot.admin.turbine.clusters 可用Turbine组列表 "default"

4.4.3. Activiti UI Module


Activiti模块显示来自/activiti端点的信息

1.将ui模块添加到类路径中:

pom.xml

dependency
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-server-ui-activiti</artifactId>
    <version>1.5.7</version>
</dependency>

2.将/activiti添加到代理端点

application.yml

4.4.4. 登录UI 模块

默认的spring boot admin server是没有做登录验证的。

Login模块只为您提供登录页面和注销按钮

1.将ui模块添加到类路径中:


<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-server-ui-login</artifactId>
    <version>1.5.7</version>
</dependency>

5.安全

  5.1保护Spring Boot Admin Server

由于解决分布式Web应用程序中的身份验证和授权有多种方法,因此Spring Boot Admin不提供默认方法。 如果在依赖项中包含spring-boot-admin-server-ui-login,它将提供登录页面和注销按钮。

Spring Security配置可能如下所示:

 @Configuration
  public static class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
      // Page with login form is served as /login.html and does a POST on /login
      http.formLogin().loginPage("/login.html").loginProcessingUrl("/login").permitAll();
      // The UI does a POST on /logout on logout
      http.logout().logoutUrl("/logout");
      // The ui currently doesn't support csrf
      http.csrf().disable();
 
      // Requests for the login page and the static assets are allowed
      http.authorizeRequests()
          .antMatchers("/login.html", "/**/*.css", "/img/**", "/third-party/**")
          .permitAll();
      // ... and any other request needs to be authorized
      http.authorizeRequests().antMatchers("/**").authenticated();
 
      // Enable so that the clients can authenticate via HTTP basic for registering
      http.httpBasic();
    }
  }

具体完成配置如下:

package org.niugang.config;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 * 基于安全认证的spring boot admin
 * 
 * @author niugang
 *
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// Page with login form is served as /login.html and does a POST on /login
		http.formLogin().loginPage("/login.html").loginProcessingUrl("/login").permitAll();
		// The UI does a POST on /logout on logout
		http.logout().logoutUrl("/logout");
		// The ui currently doesn't support csrf
		http.csrf().disable();
 
		// Requests for the login page and the static assets are allowed
		//允许登录页面和静态资源的请求
		http.authorizeRequests()
				.antMatchers("/login.html", "/**/*.css", "/img/**", "/third-party/**")
				.permitAll();
		// ... and any other request needs to be authorized
		//这点重要:所有请求都需要认证
		http.authorizeRequests().antMatchers("/**").authenticated();
 
		// Enable so that the clients can authenticate via HTTP basic for registering
		http.httpBasic();
	}
}

注意:

如果保护/api/applications端点,请不要忘记使用spring.boot.admin.username和spring.boot.admin.password在SBA客户端上配置用户名和密码【否则你的client端信息注册不到server端上】。

官方示例地址:https://github.com/codecentric/spring-boot-admin/blob/1.5.x/spring-boot-admin-samples

5.2保护客户端Actuator端点

使用HTTP基本身份验证保护Actuator点时,SBA服务器需要凭据才能访问它们。 注册应用程序时,您可以在元数据中提交凭据。 然后,BasicAuthHttpHeaderProvider使用此元数据添加Authorization标头以访问应用程序的执行器端点。 您可以提供自己的HttpHeadersProvider来改变行为(例如添加一些解密)或添加额外的标头。

使用SBA客户端提交凭据:

application.yml

spring.boot.admin:
  url: http://localhost:8080
  client:
    metadata:
      user.name: ${security.user.name}
      user.password: ${security.user.password}

使用Eureka提交凭据:

application.yml

eureka:
  instance:
    metadata-map:
      user.name: ${security.user.name}
      user.password: ${security.user.password}

 注意:SBA服务器屏蔽HTTP接口中的某些元数据,以防止泄漏敏感信息。

在通过元数据提交凭据时,应为SBA服务器或(服务注册表)配置HTTPS。

使用Spring Cloud Discovery时,您必须意识到任何可以查询服务注册表的人都可以获取凭据。

猜你喜欢

转载自blog.csdn.net/niugang0920/article/details/82558745