Spring Boot Admin 参考指南

简介: 该篇文章,由浅入深的介绍了Spring Boot Admin 的特性以及自定义二次开发,想要快速使用,请点击【快速开始】,想要深入了解的继续往下阅读
大家好,欢迎来到:clap: 阿提说说:clap:博客
该篇文章,由浅入深的介绍了Spring Boot Admin 的特性以及自定义二次开发,想要快速使用,请点击【快速开始】,想要深入了解的继续往下阅读。
Spring Boot Admin 2.5.1
Johannes Edmeier @joshiste Version 2.5.1,23.08.2021

1.什么是Spring Boot Admin

codecentric 的Spring Boot Admin 是一个社区项目,能够监控和管理您的Spring Boot 应用。这些应用通过Http注册到Spring Boot Admin 或者通过Spring Cloud的注册中心(如Eureka、Consul)来发现。UI是Spring Boot Actuator端点上的Vue.js应用。

使用Pyctuator可以支持监控Python应用程序。

2.快速开始

2.1 设置Spring Boot Admin Server

首先,需要设置一下服务端,只需要通过start.spring.io创建一个简单的Spring Boot项目。由于Spring Boot Admin Server能够做为servlet或webflux应用运行,因此您需要决定添加对应的Spring Boot Starter。在这个例子中,我们使用servlet web starter。

1.添加Spring Boot Admin启动器到依赖
pom.xml

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.5.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

:triangular_flag_on_post:
如果要使用snapshot版本的Spring boot Admin Server,您可能需要把spring 和 sonatype的快照仓库加到pom中
pom.xml

<repositories>
   <repository>
       <id>spring-milestone</id>
       <snapshots>
           <enabled>false</enabled>
       </snapshots>
       <url>http://repo.spring.io/milestone</url>
   </repository>
   <repository>
       <id>spring-snapshot</id>
       <snapshots>
           <enabled>true</enabled>
       </snapshots>
       <url>http://repo.spring.io/snapshot</url>
   </repository>
   <repository>
      <id>sonatype-nexus-snapshots</id>
       <name>Sonatype Nexus Snapshots</name>
       <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
      <snapshots>
         <enabled>true</enabled>
      </snapshots>
      <releases>
          <enabled>false</enabled>
      </releases>
   </repository>
</repositories>

2.通过添加@EnableAdminServer配置引入Spring Boot Admin Server配置

@Configuration
@EnableAutoConfiguration
@EnableAdminServer
public class SpringBootAdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAdminApplication.class, args);
    }
}
:triangular_flag_on_post:
如果想要在war包中配置Spring Boot Admin Server,并部署在servlet容器中,请查看 spring-boot-admin-sample-war

另外可以参考spring-boot-admin-sample-servlet项目,该项目增加了安全性校验

2.2 注册客户端应用程序

要在Spring Boot Admin Server(后面简称SBA) 注册您的应用程序,您可以包含SBA客户端或使用Spring Cloud Discovery(如Eureka,Consul等),SBA服务端也提供静态配置选项。

2.2.1 Spring Boot Admin 客户端

每个要注册的应用程序都必须包含Spring Boot Admin Client,为了更好的保护端点,也将spring-boot-starter-security添加到依赖中。

1.将spring-boot-admin-starter-client 添加到依赖中
pom.xml

<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>2.5.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2.配置SBA Server 的URL来开启SBA Client
application.properties

#SBA Server 注册地址
spring.boot.admin.client.url=http://localhost:8080  
#公开所有端点,生产环境应该仔细选择要公开的端点
management.endpoints.web.exposure.include=*  

3.使actuator端点可访问

@Configuration
public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll()  
            .and().csrf().disable();
    }
}

permitAll为了简洁起见,这里禁用了安全校验。查看安全部分了解如何处理安全端点。

2.2.2 Spring Cloud Discovery

如果您已经使用了Spring Cloud Discovery,那么不需要SBA客户端。只需要将DiscoveryClient添加到Spring Boot Admin Server中,其余部分由AutoConfiguration自动完成。

下面的示例使用了Eureka,但也支持其他实现了Spring Cloud Discovery的注册中心。点击链接查看ConsulZookeeper的例子。

其他,请看Spring Cloud 文档

1.添加spring-cloud-starter-eureka 到依赖中
pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2.添加@EnableDiscoveryClient配置来开启发现

@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
@EnableScheduling
@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();
        }
    }
}

permitAll为了简洁起见,这里禁用了安全校验。查看安全部分了解如何处理安全端点。

3.配置Eureka客户端
application.yml

#配置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

其他参考 spring-boot-admin-sample-eureka示例。

:triangular_flag_on_post:
您可以将SBA Server包含在Eureka的服务端中,同上面的配置,另外设置 spring.boot.admin.context-path为不同的地址,以避免SBA UI 不会与Eureka的产生冲突。

阿提说说(itsaysay),PM:2022年7月2日01:08:02

2.2.3 使用Pyctuator注册Python应用

您可以轻松的使用Pyctuator将SBA和Flask或者FastAPI集成。

下面的步骤使用Flask,但是也支持其他web框架。请查看Pyctuator文档浏览支持的框架和功能列表。

1.安装pyctuator

pip install pyctuator

2.开启pyctuator,将其指向Flask应用程序,并配置Spring Boot Admin地址

import os
from flask import Flask
from pyctuator.pyctuator import Pyctuator

app_name = "Flask App with Pyctuator"
app = Flask(app_name)


@app.route("/")
def hello():
    return "Hello World!"


Pyctuator(
    app,
    app_name,
    app_url="http://example-app.com",
    pyctuator_endpoint_url="http://example-app.com/pyctuator",
    registration_url=os.getenv("SPRING_BOOT_ADMIN_URL")
)

app.run()

更多功能和示例,请查看Pyctuator文档示例

3.客户端应用

3.1 在Application列表显示版本

对于Spring Boot应用程序来说,显示版本最简单的办法是使用spring-boot-maven-plugin生成build-info文件META-INF/build-info.properties。另请参考Spring Boot参考指南

对于非Spring Boot应用程序,您也可以添加version或build.version注册元数据,版本将显示在Application列表中。
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 管理

要在admin UI中使用JMX-beans,必须将Jolokia引入到您的应用程序中。由于Jolokia是基于servlet的,所以不支持响应式应用程序。如果您已经引入了spring-boot-admin-starter-client,它会被自动引入,如果没有就需要添加Jolokia依赖。在Spring Boot 2.2.0中,如果您想要通过JMX管理Spring beans,您需要设置spring.jmx.enabled=true
pom.mxl

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

3.3 日志文件查看器

默认情况下,日志文件无法通过actuator端点访问。为了开启日志文件端点,您需要配置Spring Boot 以生成日志文件,方法是设置logging.file.path或者logging.file.name

SBA还支持ANSI颜色转义,您需要设置自定义日志文件,SBA 日志默认是不使用颜色的。

application.properties

#日志写入目标文件
logging.file.name=/var/log/sample-boot-application.log 
#日志文件使用ANSI颜色转义
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

3.4 每个实例显示标签

Tags是一种为每个实例添加可视标记的方法,它们将出现在应用程序列表以及实例视图中。默认情况下,不向实例添加任何标记,由客户端通过向元数据或信息端点添加信息来指定所需的标记。

application.properties

#使用元数据
spring.boot.admin.client.instance.metadata.tags.environment=test

#使用info端点
info.tags.environment=test

3.5 Spring Boot Admin Client

Spring Boot Admin Client 会向Admin 服务端注册应用程序。这是通过Client定期向Admin服务端发送HTTP POST请求来完成的。

:triangular_flag_on_post:
SBA客户端注册应用程序有很多属性可以使用,如果这不符合您的需求,您可以自己实现ApplicationFactory。

Table 1. Spring Boot Admin Client 属性配置选项

Property name Description Default value
spring.boot.admin.client.enabled 开启 Spring Boot Admin 客户端 true
spring.boot.admin.client.url 要注册的SBA服务端地址列表,逗号分割。这会触发强制性自动配置
spring.boot.admin.client.api-path 管理Admin服务端上注册端点的HTTP路径 "instances"
spring.boot.admin.client.username spring.boot.admin.client.password 使用用户名和密码保护SBA服务端的API
spring.boot.admin.client.period 重复注册间隔(毫秒) 10,000
spring.boot.admin.client.connect-timeout 注册应用时的连接超时时间(毫秒) 5,000
spring.boot.admin.client.read-timeout 注册应用时的读取超时时间(毫秒) 5,000
spring.boot.admin.client.auto-registration 为true时,表示在应用程序准备就绪后通过定时任务自动注册应用 true
spring.boot.admin.client.auto-deregistration ture时,启用在关闭上下文时自动注销SBA服务端上的应用,如果没有设置,但检测到正在运行的CloudPlatform时,该功能会处于活动状态 null
spring.boot.admin.client.register-once 为true,则客户端将(按照“spring.boot.admin.instance.url”定义的顺序)仅针对一个SBA服务端进行注册;如果该SBA服务端关闭,则将自动注册到下一个服务端。如果为false,将针在所有的服务端进行注册。 true
spring.boot.admin.client.instance.health-url 健康检测URL。如果URL不同(如:Docker),则可以覆盖,但必须唯一 Guessed based on management-url and endpoints.health.id.
spring.boot.admin.client.instance.management-base-url 用于计算要注册的管理URL的基本URL。该路径是在运行时推断的,并附加到基本URL Guessed based on management.port, service-url and server.servlet-path.
spring.boot.admin.client.instance.management-url 要注册的management-url。如果可访问的URL不同(例如Docker),则可以覆盖 Guessed based on management-base-url and management.context-path.
spring.boot.admin.client.instance.service-base-url 用于计算要注册的service-url的基本URL。该路径是在运行时推断的,并附加到基本URL。在Cloudfoundry中,可以像下面这样切换到https:spring.boot.admin.client.instance.service-base-url=https://${vcap.application.uris[0]} Guessed based on hostname, server.port.
spring.boot.admin.client.instance.service-url 要注册的服务网址。如果可访问的URL不同(例如Docker),则可以覆盖 Guessed based on service-base-url and server.context-path.
spring.boot.admin.client.instance.service-path 要注册的service-path,如果路径不同(如用编程方式设置的context-path),则可以覆盖。 /
spring.boot.admin.client.instance.name 要注册的实例名称 如果设置了${spring.application.name} ,那么原来的值将被覆盖
spring.boot.admin.client.instance.prefer-ip 使用ip地址而不是主机名,如果server.address / management.address已经设置,则可以使用,否则从InetAddress.getLocalHost()获取 false
spring.boot.admin.client.instance.metadata.* 要与此实例相关联的元数据键值对
spring.boot.admin.client.instance.metadata.tags.* 要与此实例相关联的Tags键值对

Table 2.实例元数据

Key Value Default value
user.name user.password 访问端点的凭证

4.Spring Boot Admin Server

4.1 在反向代理下面运行

如果SBA 服务端运行在反向代理服务器下面,可能需要进行配置,可以通过(spring.boot.admin.ui.public-url)来访问服务器的公共url。另外当反向代理终止https连接时,可能需要配置server.forward-headers-strategy=native (also see Spring Boot Reference Guide)。

4.2 属性配置选项

Property name Description Default value
spring.boot.admin.server.enabled 开启 Spring Boot Admin Server. true
spring.boot.admin.context-path 用作Admin Server静态资源和API路径的前缀,相当于Dispatcher-Servlet
spring.boot.admin.monitor.status-interval 检查实例状态的时间间隔 10,000ms
spring.boot.admin.monitor.status-lifetime 状态的生存期。只要最后一个状态未过期,状态就不会更新。 10,000ms
spring.boot.admin.monitor.info-interval 检查实例信息的时间间隔。 1m
spring.boot.admin.monitor.info-lifetime 信息的生存期。只要最后一条信息未过期,该信息就不会更新。 1m
spring.boot.admin.monitor.default-timeout 发出请求时的默认超时。可以使用覆盖特定端点的单个值spring.boot.admin.monitor.timeout.*. 10,000
spring.boot.admin.monitor.timeout.* 端点ID和超时时间的Key-Value键值对。 默认为默认超时。
spring.boot.admin.monitor.default-retries 失败请求的默认重试次数。Modyfing请求(PUT,POST,PATCH,DELETE)将永远不会重试。spring.boot.admin.monitor.retries.*可以覆盖指定端点的单个值 0
spring.boot.admin.monitor.retries.* 键值对,端点ID的重试次数。默认为默认重试。Modyfing请求(PUT,POST,PATCH,DELETE)将永远不会重试
spring.boot.admin.metadata-keys-to-sanitize 要被过滤掉的元数据(当与正则表达式相匹配时,这些数据会在输出的json数据中过滤掉) ".**password$", ".\*secret$", ".\*key$", ".\*token$", ".\*credentials.**", ".*vcap_services$"
spring.boot.admin.probed-endpoints Spring Boot 1.x 版本指定的检查端点,如果路径与id不同,您可以将其指定为id:path(如health:ping) "health", "env", "metrics", "httptrace:trace", "threaddump:dump", "jolokia", "info", "logfile", "refresh", "flyway", "liquibase", "heapdump", "loggers", "auditevents"
spring.boot.admin.instance-auth.enabled 启用从spring配置属性中提取凭据 true
spring.boot.admin.instance-auth.default-user-name 用于对注册服务进行身份认证的默认用户名。 spring.boot.admin.instance-auth.enabled 配置必须是true null
spring.boot.admin.instance-auth.default-password 用于对注册服务进行身份认证的默认用户密码。spring.boot.admin.instance-auth.enabled 配置必须是 true. null
spring.boot.admin.instance-auth.service-map.*.user-name 用于对指定名称的注册服务进行身份验证的用户名。 spring.boot.admin.instance-auth.enabled 必须是 true.
spring.boot.admin.instance-auth.service-map.*.user-password 用于对指定名称的注册服务进行身份验证的用户密码。 spring.boot.admin.instance-auth.enabled 必须是 true.
spring.boot.admin.instance-proxy.ignored-headers 不向客户端发送的header "Cookie", "Set-Cookie", "Authorization"
spring.boot.admin.ui.public-url 用于在ui中构建基本href的基本URL 如果在反向代理后面运行(使用路径重写),则可用于进行正确的自我引用。如果省略了主机/端口,将从请求中推断出来
spring.boot.admin.ui.brand 导航栏中显示的品牌 "<img src="assets/img/icon-spring-boot-admin.svg"><span>Spring Boot Admin</span>"
spring.boot.admin.ui.title 要显示的页面标题 "Spring Boot Admin"
spring.boot.admin.ui.login-icon 登录页面上的图标 "assets/img/icon-spring-boot-admin.svg"
spring.boot.admin.ui.favicon 用作默认图标的图标,用于桌面通知的图标 "assets/img/favicon.png"
spring.boot.admin.ui.favicon-danger 当一项或多项服务关闭并用于桌面通知时,用作网站图标 "assets/img/favicon-danger.png"
spring.boot.admin.ui.remember-me-enabled 登录界面remember-me开关 true
spring.boot.admin.ui.poll-timer.cache 获取新缓存数据的轮询持续时间(毫秒) 2500
spring.boot.admin.ui.poll-timer.datasource 获取新数据源数据的轮询持续时间(毫秒) 2500
spring.boot.admin.ui.poll-timer.gc 获取新gc数据的轮询持续时间(毫秒) 2500
spring.boot.admin.ui.poll-timer.process 获取新过程数据的轮询持续时间(毫秒) 2500
spring.boot.admin.ui.poll-timer.memory 获取新内存数据的轮询持续时间(毫秒) 2500
spring.boot.admin.ui.poll-timer.threads 获取新线程数据的轮询持续时间(毫秒) 2500

4.3 Spring Cloud Discovery

SBA 服务端能通过DiscoveryClient发现应用程序。优点是客户端不需要引入spring-boot-admin-starter-client依赖。你只需要添加一个DiscoveryClient的实现,其他都有AutoConfiguration自动完成。

4.3.1 SimpleDiscoveryClient静态配置

Spring Cloud 提供了SimpleDiscoveryClient。它允许您通过静态配置来指定客户端应用程序。
pom.xml

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

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.3.2 其他DiscoveryClients

Spring Boot Admin 支持所有实现了Spring Cloud DiscoveryClient的组件(如Eureka, Zookeeper, Consul...)。您需要添加它到Spring Boot Admin Server中,并正确配置。

4.3.3 转换ServiceInstances

服务注册信息通过ServiceInstanceConverter转换,SBA附带默认转换和Eureka的转换实现。通过AutoConfiguration会自动选择一个正确的实现。

:triangular_flag_on_post:
您可以使用SBA服务端配置选项和实例的元数据来修改注册表中的信息。元数据中的值优先于服务器配置。如果配置选项不满足需求,您可以提供自己的 ServiceInstanceConverter

:heavy_exclamation_mark:
当使用Eureka时,已经知道了healthCheckUrl用于Eureka监控检查,您可以在Eureka的客户端配置eureka.instance.healthCheckUrl

Table 3. 实例元数据选项

Key Value Default value
user.name user.password 用于访问端点的凭据。
management.scheme 该scheme值在service URL中替换以便访问actuator端点。
management.address 该address值在service URL中替换以便访问actuator端点。
management.port 该port值在service URL中替换以便访问actuator端点。
management.context-path 该路径将会追加在service URL中,用于访问actuator端点 ${spring.boot.admin.discovery.converter.management-context-path}
health.path 该路径将会追加在service URL中,用于健康检查。忽略 EurekaServiceInstanceConverter. ${spring.boot.admin.discovery.converter.health-endpoint}

Table 4. Discovery配置选项

Property name Description Default value
spring.boot.admin.discovery.enabled 启用对Admin 服务端的DiscoveryClient支持 true
spring.boot.admin.discovery.converter.management-context-path DefaultServiceInstanceConverter转换management-url时,将附加到发现服务的服务url。 /actuator
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*")。 "*"
spring.boot.admin.discovery.ignored-instances-metadata 如果服务实例至少包含一个与此列表匹配的元数据项,则将忽略这些实例。(e.g. "discoverable=false")
spring.boot.admin.discovery.instances-metadata 如果服务实例包含至少一个与此列表匹配的元数据项,则将包括这些实例。 (e.g. "discoverable=true")

4.3.4 CloudFoundry

如果您将应用部署在CloudFoundry,那么vcap.application.application_id vcap.application.instance_index必须配置在元数据中,以便正确注册到SBA 服务中。如下是关于Eureka的简单示例:

application.yml

eureka:
  instance:
    hostname: ${vcap.application.uris[0]}
    nonSecurePort: 80
    metadata-map:
      applicationId: ${vcap.application.application_id}
      instanceId: ${vcap.application.instance_index}

4.4 集群

Spring Boot Admin Server支持通过Hazelcast进行群集复制。当存在HazelcastConfig或HazelcastInstance Bean时,它会自动启用。您还可以将Hazelcast配置为持久的,以便在重新启动时保持该状态。另请参阅 Spring Boot support for Hazelcast

  1. 添加Hazelcast依赖

pom.xml

<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast</artifactId>
</dependency>
  1. 实例化HazelcastConfig
@Bean
public Config hazelcastConfig() {
  // 用于存储事件的map
  // 应该要可靠的保存数据,如果事件太多,Spring Boot Admin将会进行压缩
  MapConfig eventStoreMap = new MapConfig(DEFAULT_NAME_EVENT_STORE_MAP).setInMemoryFormat(InMemoryFormat.OBJECT)
      .setBackupCount(1)
      .setMergePolicyConfig(new MergePolicyConfig(PutIfAbsentMergePolicy.class.getName(), 100));

  // 该map用于清除通知中的重复数据。
 //如果此映射中的数据丢失,这应该不是一个大问题,因为这将导致多个实例发送相同的通知
  MapConfig sentNotificationsMap = new MapConfig(DEFAULT_NAME_SENT_NOTIFICATIONS_MAP)
      .setInMemoryFormat(InMemoryFormat.OBJECT).setBackupCount(1)
      .setEvictionConfig(new EvictionConfig().setEvictionPolicy(EvictionPolicy.LRU)
          .setMaxSizePolicy(MaxSizePolicy.PER_NODE))
      .setMergePolicyConfig(new MergePolicyConfig(PutIfAbsentMergePolicy.class.getName(), 100));

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

  // WARNING: 这将设置一个本地集群,您可以根据需要对其进行更改。
  config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
  TcpIpConfig tcpIpConfig = config.getNetworkConfig().getJoin().getTcpIpConfig();
  tcpIpConfig.setEnabled(true);
  tcpIpConfig.setMembers(singletonList("127.0.0.1"));
  return config;
}

Table 5. Hazelcast 配置选项

Property name Description Default value
spring.boot.admin.hazelcast.enabled 开启Hazelcast 支持 true
spring.boot.admin.hazelcast.event-store 用于存储事件的Hazelcast-map的名称 "spring-boot-admin-event-store"
spring.boot.admin.hazelcast.sent-notifications 用于存储去重通知的Hazelcast-map的名称 "spring-boot-admin-sent-notifications"

4.5 通知

4.5.1 邮件通知

邮件通知使用Thymeleaf作为模版。要开启邮件通知,使用spring-boot-starter-mail配置JavaMailSender并设置收件人。

Figure 1. 简单的邮件通知

:heavy_exclamation_mark: 为了防止泄露敏感信息,默认邮件模板不显示实例的任何元数据。如果您想显示一些元数据,可以使用自定义模板。

1.添加spring-boot-starter-mail 依赖
pom.xml

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

2.配置JavaMailSender
application.properties

spring.mail.host=smtp.example.com
spring.boot.admin.notify.mail.to=admin@example.com

3.使用以下选项配置邮件
Table 6. 邮件通知配置选项

Property name Description Default value
spring.boot.admin.notify.mail.enabled 开启邮件通知 true
spring.boot.admin.notify.mail.ignore-changes 要忽略的状态变更: ":"。允许使用通配符 "UNKNOWN:UP"
spring.boot.admin.notify.mail.template 用于渲染的Thymeleaf模板的资源路径。 "classpath:/META-INF/spring-boot-admin-server/mail/status-changed.html"
spring.boot.admin.notify.mail.to 以逗号分隔的邮件收件人列表 "root@localhost"
spring.boot.admin.notify.mail.cc 以逗号分隔的抄送收件人列表
spring.boot.admin.notify.mail.from 邮件发送人 "Spring Boot Admin <noreply@localhost>"
spring.boot.admin.notify.mail.additional-properties 可以从模板访问的其他属性

4.5.3 OpsGenie通知 1

要启用OpsGenie通知,您只需将新的JSON Rest API集成添加到您的OpsGenie帐户并设置接收的apiKey spring.boot.admin.notify.opsgenie.api-key

Table 8. OpsGenie 通知配置选项

Property name Description Default value
spring.boot.admin.notify.opsgenie.enabled 开启OpsGenie 通知 true
spring.boot.admin.notify.opsgenie.ignore-changes 要忽略的状态变更 <from-status>:<to-status>。允许使用通配符 "UNKNOWN:UP"
spring.boot.admin.notify.opsgenie.api-key opsgenie的apikey
spring.boot.admin.notify.opsgenie.url OpsGenie 告警url "https://api.opsgenie.com/v2/alerts"
spring.boot.admin.notify.opsgenie.description 描述事件的说明,支持SpEL表达式。 "#{instance.registration.name}/#{instance.id} is #{instance.statusInfo.status}"
spring.boot.admin.notify.opsgenie.actions 可以执行的动作,逗号分隔
spring.boot.admin.notify.opsgenie.source 用于指定警报源的字段。默认情况下,它将被分配到传入请求的IP地址。
spring.boot.admin.notify.opsgenie.tags 附加到警报的标签的逗号分隔列表。
spring.boot.admin.notify.opsgenie.entity 与警报相关的实体。
spring.boot.admin.notify.opsgenie.user 执行的默认所有者。如果未指定用户,系统将成为执行的所有者。

4.5.4 Hipchat 通知

开启Hipchat通知,您仅仅需要用您的Hipchat账户创建一个API token,并设置正确的配置。
Table 9. Hipchat 通知配置选项

Property name Description Default value
spring.boot.admin.notify.hipchat.enabled 开启Hipchat通知 true
spring.boot.admin.notify.hipchat.ignore-changes 要忽略的状态变更<from-status>:<to-status>。允许使用通配符。 "UNKNOWN:UP"
spring.boot.admin.notify.hipchat.url HipChat 的REST API (V2) URL
spring.boot.admin.notify.hipchat.auth-token 可访问的API Token
spring.boot.admin.notify.hipchat.room-id 要向其发送通知的房间的ID或url-encoded的名称
spring.boot.admin.notify.hipchat.notify 消息是否应触发用户通知 false
spring.boot.admin.notify.hipchat.description 描述事件的说明,支持SpEL表达式。 "<strong>#{instance.registration.name}</strong>/#{instance.id} is <strong>#{event.statusInfo.status}</strong>"

4.5.5 Slack 通知

要启用Slack通知,您需要在Slack帐户的自定义集成下添加一个传入的Webhook,并对其进行适当配置。

Table 10. Slack 通知配置选项

Property name Description Default value
spring.boot.admin.notify.slack.enabled 开启Slack通知 true
spring.boot.admin.notify.slack.ignore-changes 要忽略的状态变更<from-status>:<to-status>。允许使用通配符。 "UNKNOWN:UP"
spring.boot.admin.notify.slack.webhook-url 发送Slack通知的 Webhook 地址
spring.boot.admin.notify.slack.channel 可选频道名称(开头没有#)。如果与Slack Webhooks设置中的频道不同
spring.boot.admin.notify.slack.icon 可选的icon名称(周围没有冒号)。 如果与Slack Webhooks设置中的频道不同
spring.boot.admin.notify.slack.username 可选的发送用户名。 如果与Slack Webhooks设置中的频道不同 Spring Boot Admin
spring.boot.admin.notify.slack.message 描述事件的说明,支持SpEL表达式。 "*#{instance.registration.name}* (#{instance.id}) is *#{event.statusInfo.status}*"

4.5.6 Let's Chat 通知

要启用Let's Chat通知,您需要添加host url,并从Let's Chat中添加API令牌和用户名。

Table 11. Let’s Chat 通知配置选项

Property name Description Default value
spring.boot.admin.notify.letschat.enabled 开启let´s Chat 通知 true
spring.boot.admin.notify.letschat.ignore-changes 要忽略的状态变更<from-status>:<to-status>。允许使用通配符。 "UNKNOWN:UP"
spring.boot.admin.notify.letschat.url 要发送的通知的let´s Chat host地址
spring.boot.admin.notify.letschat.room 要发送消息房间
spring.boot.admin.notify.letschat.token 访问let´s Chat API的token
spring.boot.admin.notify.letschat.username 创建token 的用户名 Spring Boot Admin
spring.boot.admin.notify.letschat.message 描述事件的说明,支持SpEL表达式。 "*#{instance.registration.name}* (#{instance.id}) is *#{event.statusInfo.status}*"

4.5.7 Microsoft Teams通知

要启用Microsoft团队通知,您需要设置连接器的webhook url地址并设置适当的配置属性。

Table 12. Microsoft Teams 通知配置选项

Property name Description Default value
spring.boot.admin.notify.ms-teams.enabled 开启Microsoft Teams通知 true
spring.boot.admin.notify.ms-teams.webhook-url Microsoft Teams webhook url地址
spring.boot.admin.notify.ms-teams.deRegisteredTitle 应用程序注销时Teams消息的标题。 De-Registered
spring.boot.admin.notify.ms-teams.registeredTitle 应用程序注册时Teams消息的标题。 Registered
spring.boot.admin.notify.ms-teams.statusChangedTitle 应用程序状态变更时Teams消息的标题 Status Changed
spring.boot.admin.notify.ms-teams.messageSummary Teams消息的摘要 Spring Boot Admin Notification
spring.boot.admin.notify.ms-teams.theme_color 设置消息颜色。支持SpEL表达式 #{event.type == 'STATUS_CHANGED' ? (event.statusInfo.status=='UP' ? '6db33f' : 'b32d36') : '439fe0'}
spring.boot.admin.notify.ms-teams.deregister_activity_subtitle 应用程序注销时Teams消息活动部分的副标题。支持SpEL表达式 #{instance.registration.name} with id #{instance.id} has de-registered from Spring Boot Admin
spring.boot.admin.notify.ms-teams.register_activity_subtitle 应用程序注册时Teams消息活动部分的副标题。支持SpEL表达式 #{instance.registration.name} with id #{instance.id} has registered with Spring Boot Admin
spring.boot.admin.notify.ms-teams.status_activity_subtitle 应用程序状态变更时Teams消息活动部分的副标题。支持SpEL表达式 #{instance.registration.name} with id #{instance.id} changed status from #{lastStatus} to #{event.statusInfo.status}

4.5.8 Telegram 通知

要启用Telegram通知,您需要创建并授权一个机器人,并设置正确的auth-tokenchat-id

Table 13. Telegram 通知配置选项

Property name Description Default value
spring.boot.admin.notify.telegram.enabled 开启Telegram 通知 true
spring.boot.admin.notify.telegram.auth-token Telegram 机器人授权Token(如123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11).
spring.boot.admin.notify.telegram.chat-id 目标聊天的唯一标识符或目标频道的用户名
spring.boot.admin.notify.telegram.disable-notify 如果是true,用户将收到一个没有声音的通知。 false
spring.boot.admin.notify.telegram.parse_mode 发送消息的格式化模式. 当前支持HTML 和 Markdown 'HTML'
spring.boot.admin.notify.telegram.message 发送的文本。支持SpEL表达式 "<strong>#{instance.registration.name}</strong>/#{instance.id} is <strong>#{event.statusInfo.status}</strong>"

4.5.9 Discord通知

要启用Discord通知,您需要创建webhook并设置适当的配置属性。

Table 14. Discord 通知配置选项

Property name Description Default value
spring.boot.admin.notify.discord.enabled 开启Discord通知 true
spring.boot.admin.notify.discord.webhook-url 发送通知的webhook url
spring.boot.admin.notify.discord.username 可选用户名 Default set in Discord
spring.boot.admin.notify.discord.avatar-url 可选的头像URL Default set in Discord
spring.boot.admin.notify.discord.tts 文本消息是否转换成语音 false
spring.boot.admin.notify.discord.message 发送的文本。支持SpEL表达式 "*#{instance.registration.name}* (#{instance.id}) is *#{event.statusInfo.status}*"

4.5.10 通知代理设置

所有使用RestTemplate的通知程序都可以配置为使用代理。

Table 15. Notification Proxy 配置选项

Property name Description Default value
spring.boot.admin.notify.proxy.host 代理地址
spring.boot.admin.notify.proxy.port 代理端口
spring.boot.admin.notify.proxy.username 鉴权用户名(如果需要)
spring.boot.admin.notify.proxy.password 鉴权密码(如果需要)

4.5.11 通知提醒

RemindingNotifier 为down/offline的应用程序发送提醒,它可以将发送通知委托给另一个应用程序。

应用程序默认在状态变为DOWN或者OFFLINE是触发提醒。您可以通过setReminderStatuses()修改该行为。当状态更改为非触发状态或相关应用程序注销时,提醒结束。

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

如何配置提醒

@Configuration
public class NotifierConfiguration {
    @Autowired
    private Notifier notifier;

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

4.5.12 过滤通知

FilteringNotifier 允许您在运行时根据规则过滤某些通知。它将通知发送委托给另一个通知程序。

如果您添加FilteringNotifier 到您的ApplicationContext中,notifications/filter上的RESTful接口可用。

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

如何配置filtering

@Configuration(proxyBeanMethods = false)
public class NotifierConfig {

  private final InstanceRepository repository;

  private final ObjectProvider<List<Notifier>> otherNotifiers;

  public NotifierConfig(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);
  }

    //使用FilterInNotifier作为委托,将RemindingNotifier 做为主bean
  @Primary
  @Bean(initMethod = "start", destroyMethod = "stop")
  public RemindingNotifier remindingNotifier() { 
    RemindingNotifier notifier = new RemindingNotifier(filteringNotifier(), this.repository);
    notifier.setReminderPeriod(Duration.ofMinutes(10));
    notifier.setCheckReminderInverval(Duration.ofSeconds(10));
    return notifier;
  }

}
:heavy_exclamation_mark: 本例结合了提醒和过滤通知。这允许您部署的应用程序在一定时间内(直到过滤器过期)没有重新启动后获取通知。

4.5.13 钉钉通知

要开启DingTalk通知,您需要创建一个钉钉机器人,并正确设置webhookUrl 和秘钥

Table 16. DingTalk 通知配置选项

Property name Description Default value
spring.boot.admin.notify.dingtalk.enabled 开启钉钉通知 true
spring.boot.admin.notify.dingtalk.webhook-url DingTalk webhook URL地址
spring.boot.admin.notify.dingtalk.secret 消息秘钥
spring.boot.admin.notify.dingtalk.message 发送的文本。支持SpEL表达式 "#{instance.registration.name} #{instance.id} is #{event.statusInfo.status} "

5. 安全

5.1 Spring Boot Admin Server 安全

由于有几种方法可以解决分布式web应用程序中的身份验证和授权问题,因此Spring Boot Admin没有提供默认方法。spring-boot-admin-server-ui默认会提供一个登录页面和登出。

Spring Security配置在服务端看起来像这样:

@Configuration(proxyBeanMethods = false)
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

  private final AdminServerProperties adminServer;

  private final SecurityProperties security;

  public SecuritySecureConfig(AdminServerProperties adminServer, SecurityProperties security) {
    this.adminServer = adminServer;
    this.security = security;
  }

  @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("/actuator/info")).permitAll()
            .antMatchers(this.adminServer.path("/actuator/health")).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()) 
    //使用Cookie启用CSRF保护
       .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 
       //禁用Spring Boot管理客户端用于(取消)注册的端点的CSRF保护。
           .ignoringRequestMatchers(
                new AntPathRequestMatcher(this.adminServer.path("/instances"),
                    HttpMethod.POST.toString()), 
                new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
                    HttpMethod.DELETE.toString()), 
                    //禁用actuator端点的CSRF保护
                new AntPathRequestMatcher(this.adminServer.path("/actuator/**")) 
            ))
        .rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
  }

  // Required to provide UserDetailsService for "remember functionality"
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser(security.getUser().getName())
        .password("{noop}" + security.getUser().getPassword()).roles("USER");
  }

}

如果您使用Spring Boot Admin客户端,它需要访问服务器的凭据:
application.yml

spring.boot.admin.client:
   username: sba-client
   password: s3cret

有关完整的示例,请参阅spring-boot-admin-sample-servlet

:heavy_exclamation_mark: 如果您设置了保护 /instances端点,那么不要忘记在SBA-Client客户端设置用户名和密码 spring.boot.admin.client.usernamespring.boot.admin.client.password

5.2 保护客户端Actuator端点

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

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

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

:heavy_exclamation_mark:使用Spring Cloud Discovery时,您必须知道,任何可以查询您的服务注册表的人都可以获得凭据。

💡使用这种方法时,SBA服务器决定用户是否可以访问已注册的应用程序。可能有更复杂的解决方案(使用OAuth2)让客户端决定用户是否可以访问端点。您可以查看示例joshiste/spring-boot-admin-samples

5.2.1 SBA客户端

application.yml

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

5.2.2 SBA服务端

您可以在Admin服务端中通过配置属性指定凭据。

💡您可以将其与 spring cloud kubernetes结合使用,从 secrets中提取凭据。

启用从属性中提取凭据,spring.boot.admin.instance-auth.enabled必须设置为true(默认)。

:heavy_exclamation_mark:如果您的客户端通过元数据提供凭据,则将使用该元数据而不是属性。

您可以通过 spring.boot.admin.instance-auth.default-user-namespring.boot.admin.instance-auth.default-user-password设置默认用户名和密码。(可选的)您可以提供指定服务的凭据(按名称)spring.boot.admin.instance-auth.service-map.*.user-name,将*代替为具体的服务名。

application.yml

spring.boot.admin:
  instance-auth:
    enabled: true
    default-user-name: "${some.user.name.from.secret}"
    default-password: "${some.user.password.from.secret}"
    service-map:
      my-first-service-to-monitor:
        user-name: "${some.user.name.from.secret}"
        user-password: "${some.user.password.from.secret}"
      my-second-service-to-monitor:
        user-name: "${some.user.name.from.secret}"
        user-password: "${some.user.password.from.secret}"

5.2.3 Eureka

application.yml

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

5.2.4 Consul

application.yml

spring.cloud.consul:
  discovery:
    metadata:
        user-name: ${spring.security.user.name}
        user-password: ${spring.security.user.password}
:heavy_exclamation_mark: Consul 不允许 .在元数据key中,请改用 -

5.2.5 Actuator端点上的 CSRF

一些actuator 端点(如:/loggers)支持POST请求。但使用Spring Security 时,您需要忽略端点上的CSRF保护,因为当前Spring Boot Admin Server 还缺少支持。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf()
        .ignoringAntMatchers("/actuator/**");
}

5.3 使用Mutual TLS

SBA服务器还可以在访问执行器端点时使用客户端证书进行身份验证。如果存在自定义配置的ClientHttpConnector bean,Spring Boot将自动配置WebClient.Builder,它将被SBA使用。

@Bean
public ClientHttpConnector customHttpClient() {
    SslContextBuilder sslContext = SslContextBuilder.forClient();
    //您的自定义sslContext 将转到此处
    HttpClient httpClient = HttpClient.create().secure(
        ssl -> ssl.sslContext(sslContext)
    );
    return new ReactorClientHttpConnector(httpClient);
}

6 自定义

6.1 自定义通知

您可以通过实现Notifier来自定义通知。推荐继承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());
      }
    });
  }

}

6.2 注入自定义HTTP头

如果要在监控应用程序actuator端点的请求中加入自定义的HTTP头,可以通过HttpHeadersProvider轻松实现。

@Bean
public HttpHeadersProvider customHttpHeadersProvider() {
  return (instance) -> {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("X-CUSTOM", "My Custom Value");
    return httpHeaders;
  };
}

6.3 拦截请求和响应

通过实现InstanceExchangeFilterFunction接口,可以拦截和修改对受监控应用程序的执行器端点的请求和响应。这对于审核或添加一些额外的安全检查非常有用。

@Bean
public InstanceExchangeFilterFunction auditLog() {
  return (instance, request, next) -> next.exchange(request).doOnSubscribe((s) -> {
    if (HttpMethod.DELETE.equals(request.method()) || HttpMethod.POST.equals(request.method())) {
      log.info("{} for {} on {}", request.method(), instance.getId(), request.url());
    }
  });
}

6.4 链接/嵌入外部页面

您可以非常简单的将链接或者外部页面添加到SBA,甚至是嵌入(iframe=true)

spring:
  boot:
    admin:
      ui:
        external-views:
          - label: "🚀"
            url: http://codecentric.de
            order: 2000

6.5 自定义视图

可以向ui添加自定义视图。视图必须是基于Vue.js的。

JavaScript包和CSS样式表必须放在/META-INF/spring-boot-admin-server-ui/extensions/{name}/的类路径上,以便服务器可以提取它们。

spring-boot-admin-sample-custom-ui 提供了一个简单的UI,包含构建这样一个module的必要maven配置。

自定义扩展通过SBA.use()进行自我注册,并通过install()暴露自己,当UI设置路由时调用。install() 函数接受以下参数以注册视图和回调。

如果将新的顶层路由添加到前端,后端也必须知道。在/META-INF/spring-boot-admin-server-ui/extensions/{name}/routes.txt中每行添加一个顶层路由。

6.5.1 添加顶层视图

下面是一个简单的顶层视图,列出了所有注册的应用程序:

<template>
  <pre v-text="stringify(applications, null, 4)" />
</template>

<script>
export default {
  props: {
    applications: { 
      type: Array,
      required: true
    }
  },
  methods: {
    stringify: JSON.stringify
  }
};
</script>
:heavy_exclamation_mark:如果您定义了 applications属性,那么将接受所有注册的应用程序

:bulb: 有一些有用的方法,查看 application.jsinstance.js

SBA.use({
  install({viewRegistry}) {
    viewRegistry.addView({
    //视图名称
      name: 'custom',
      //视图访问路径  
      path: '/custom',
      //导入的自定义组件
      component: custom,
      // 自定义视图在顶部导航栏显示的标签
      label: 'Custom', 
      //视图的顺序。顶部导航栏中的视图按升序排序。
      order: 1000, 
    });
  }
});

routes.txt中添加路由

/custom/**

6.5.2 可视化自定义端点

以下是显示自定义端点的视图:

<template>
  <div class="custom">
    <p>Instance: <span v-text="instance.id" /></p>
    <p>Output: <span v-text="text" /></p>
  </div>
</template>

<script>
  export default {
    props: {
    //如果定义实例属性,组件将接收应渲染视图的实例。
     instance: { 
        type: Object,
        required: true
      }
    },
    data: () => ({
      text: ''
    }),
    async created() {
    //每个实例都有一个预配置的axios实例,用于使用正确的路径和头访问端点。
     const response = await this.instance.axios.get('actuator/custom'); 
      this.text = response.data;
    }
  };
</script>

<style>
  .custom {
    font-size: 20px;
    width: 80%;
  }
</style>

注册实例视图的工作方式与顶级视图类似,具有一些附加属性:

SBA.use({
  install({viewRegistry, vueI18n}) {
    viewRegistry.addView({
      name: 'instances/custom',
      //父对象必须是实例
      parent: 'instances', 
      path: 'custom',
      component: customEndpoint,
      label: 'Custom',
      //使用组来给视图分组
      group: 'custom', 
      order: 1000,
      //您可以动态确定是否应该为特定实例显示视图
     isEnabled: ({instance}) => instance.hasEndpoint('custom') 
    });

    //自定义翻译
    vueI18n.mergeLocaleMessage('en', { 
      sidebar: {
        custom : {
          title : "My Custom Extensions"
        }
      }
    });
  }
});
:heavy_exclamation_mark: 通过设置组名和名称,可以覆盖默认的视图

PM: 2022年7月5日02:50:39

6.6 自定义头部Logo和标题

您可以通过如下的配置,在头部显示自定义信息:

  • spring.boot.admin.ui.brand: 这段HTML在头部导航中显示,默认为<img src="assets/img/icon-spring-boot-admin.svg"><span>Spring Boot Admin</span>。默认情况下显示SBA Logo 后面紧跟名称。如果你想要展示自定义的Logo,设置:spring.boot.admin.ui.brand=<img src="custom/custom-icon.png">。或者您只需要将图像添加到您Jar包的/META-INF/spring-boot-admin-server-ui/中(SBA默认从该路径注册ResourceHandler ),或者您必须确保图像得到正确的服务(如注册您自己的ResourceHandler
  • spring.boot.admin.ui.title: 使用此选项可自定义浏览器窗口标题。

6.7 自定义登录Logo

您可以设置一个自定义图片显示在登录页面。

  1. 将图像放在通过http提供服务的资源位置(如:/META-INF/spring-boot-admin-server-ui/assets/img/)
  2. 配置下面属性

spring.boot.admin.ui.login-icon: 用作登录页面上的图标 (比如 assets/img/custom-login-icon.svg)

6.8 自定义Favicon

可以使用自定义favicon,它也用于桌面通知。当一个或多个应用程序关闭时,Spring Boot Admin使用不同的图标。

  1. 放置favicon(.png至少192x192像素)在资源路径(比如:/META-INF/spring-boot-admin-server-ui/assets/img/)
  2. 配置icons

    • spring.boot.admin.ui.favicon: 用作默认图标. (比如 assets/img/custom-favicon.png
    • spring.boot.admin.ui.favicon-danger:当一个或多个服务关闭时使用。(比如 assets/img/custom-favicon-danger.png)

6.9 自定义可用语言

spring.boot.admin.ui.available-languages: 要选用的语言。 (比如 en,de out of existing de,en,fr,ko,pt-BR,ru,zh)

显示/隐藏视图

您可以很简单的在导航栏中隐藏视图:

spring:
  boot:
    admin:
      ui:
        view-settings:
          - name: "journal"
            enabled: false

7. 监控Spring Boot 1.5.x

可以使用SBA 2.x监控 SB 1.5x的应用。旧的SBA Client 可以注册在新的服务端上。由于API略有变化,您需要在旧客户端上设置以下属性:

  1. 在SBA Client 1.5x上重新配置 api路径

application.yml

spring.boot.admin.api-path: instances

随着Spring Boot 2 release 版本的发布,一些执行器端点发生了变化,并非所有选项都可用(例如/metrics端点);对于一些端点,我们提供了转换器。

PM:2022年7月5日03:23:20


  1. Atlassian出品,著名产品有Confluence
相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
28天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
43 0
|
8天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
24 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
10天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
【Spring系列】Sping VS Sping Boot区别与联系
|
2月前
|
XML 监控 druid
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
|
8月前
|
人工智能 监控 Java
SpringBoot实战(十三):Spring Boot Admin 动态修改日志级别
SpringBoot实战(十三):Spring Boot Admin 动态修改日志级别
342 0
|
8月前
|
人工智能 监控 Java
SpringBoot实战(十二):集成 Spring Boot Admin 监控
SpringBoot实战(十二):集成 Spring Boot Admin 监控
|
3月前
|
Java
springboot项目打包瘦身
springboot项目打包瘦身
|
5月前
|
Java 测试技术
Springboot集成JUnit5优雅进行单元测试
Springboot集成JUnit5优雅进行单元测试
|
7月前
|
监控 Java Nacos
Spring Boot Admin中无法监控到新服务注册的问题
Spring Boot Admin中无法监控到新服务注册的问题
220 1
|
7月前
|
监控 Java Nacos
在Spring Boot Admin中无法监控到新服务注册
在Spring Boot Admin中无法监控到新服务注册
193 1