Spring Boot Admin 2.3.1最新搭建到使用全攻略

1、什么是Spring Boot Admin?

Spring Boot Admin主要是用于管理和监控SpringBoot的应用,应用程序可以通过Spring Boot Admin Client向Admin Server进行注册或者使用Eureka、Consul这样的Spring Cloud注册中心来发现。

Spring Boot Admin为注册的应用程序提供以下功能:

  • 显示健康状况
  • 显示详细信息,例如
    • JVM和内存指标
    • micrometer.io指标
    • 数据源指标
    • 缓存指标
  • 显示内部编号
  • 关注并下载日志文件
  • 查看JVM系统和环境属性
  • 查看Spring Boot配置属性
  • 支持Spring Cloud的可发布/ env-&/ refresh-endpoint
  • 轻松的日志级别管理
  • 与JMX-beans交互
  • 查看线程转储
  • 查看http-traces
  • 查看审核事件
  • 查看http端点
  • 查看预定的任务
  • 查看和删除活动会话(使用spring-session)
  • 查看Flyway / Liquibase数据库迁移
  • 下载heapdump
  • 状态更改通知(通过电子邮件,Slack,Hipchat等)
  • 状态更改的事件日志(非持久性)

2、快速开始

2.1、 配置Spring Boot Admin Server

首先只需要简单的通过start.spring.io创建一个项目,由于Spring Boot Admin Server能够作为servlet或webflux应用程序运行,因此您需要对此进行决定并添加相应的Spring Boot Starter。在此示例中,我们使用Servlet Web Starter。

添加相关依赖

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

通过添加@EnableAdminServer到配置中来引入Spring Boot Admin Server配置

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

修改配置文件

# 应用程序名称
spring.application.name=SpringBootAdmin
# 应用程序端口
server.port=8080

第一阶段完成,此时服务已经可以正常启动。

在这里插入图片描述

2.2、配置 Spring Boot Admin Client

新创建一个项目,并添加依赖

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

修改配置文件


# 应用程序名称
spring.application.name=admin-client
# 应用程序端口
server.port=9090

# 要在其中注册的Spring Boot Admin Server的URL。
spring.boot.admin.client.url=http://localhost:8080
# 与Spring Boot 2一样,默认情况下,大多数端点都不通过http公开,我们公开了所有端点。对于生产,您应该仔细选择要公开的端点。
management.endpoints.web.exposure.include=*

启动类无需修改,直接启动项目

@SpringBootApplication
public class AdminClientApplication {

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

}

再次访问8080,成功注册

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3、结合Eureka注册中心使用

Eureka服务端、客户端搭建可以参考 SpringCloud全家桶—注册中心Eureka搭建

3.1、Admin Server注册到Eureka注册中心

在前面配置的Admin Server基础上,添加Eureka Client相关依赖。

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

启动类,添加@EnableEurekaClient,让注册中心发现

@SpringBootApplication
@EnableAdminServer
@EnableEurekaClient
public class AdminApplication {

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

修改配置项

# 应用程序名称
spring.application.name=spring-boot-admin
# 应用程序端口
server.port=8080
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

# eureka客户端配置
eureka.client.service-url.defaultZone=http://eurekaServer1.com:18001/eureka/
eureka.instance.prefer-ip-address=true
#注册中心显示的实例ID,可以用ip地址加端口来区别
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
eureka.instance.health-check-url-path=/actuator/health

启动服务,注册中心列表和admin都已经完成注册

在这里插入图片描述

3.2、Admin Client注册到Eureka注册中心

在前面Admin Client基础上,添加Eureka Client相关依赖

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

修改配置文件

# 应用程序名称
spring.application.name=admin-client
# 应用程序端口
server.port=9090
# 通过注册中心发现,就不需要自己注册了
#spring.boot.admin.client.url=http://localhost:8080
# 与Spring Boot 2一样,默认情况下,大多数端点都不通过http公开,我们公开了所有端点。对于生产,您应该仔细选择要公开的端点。
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always



# eureka客户端配置
eureka.client.service-url.defaultZone=http://eurekaServer1.com:18001/eureka/
eureka.instance.prefer-ip-address=true
#注册中心显示的实例ID,可以用ip地址加端口来区别
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
eureka.instance.health-check-url-path=/actuator/health

启动类

@SpringBootApplication
@EnableEurekaClient
public class AdminClientApplication {

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

}

服务启动,完成Eureka和Admin的注册

在这里插入图片描述

4、配置Spring Security

基于安全性方面考虑,还可以集成Security。

Admin Server端,添加Security相关依赖

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

启动类

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.util.UUID;

@SpringBootApplication
@EnableAdminServer
@EnableEurekaClient
public class AdminApplication {

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

    @Configuration
    public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

        private final AdminServerProperties adminServer;

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

        @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("/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()) // 启用HTTP基本支持。这是Spring Boot Admin Client注册所必需的。
                    .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) //使用Cookies启用CSRF保护
                            .ignoringRequestMatchers(
                                    new AntPathRequestMatcher(this.adminServer.path("/instances"),
                                            HttpMethod.POST.toString()), // 禁用Spring Boot Admin Client用于(注销)注册的端点的CSRF-Protection。
                                    new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
                                            HttpMethod.DELETE.toString()), // 禁用Spring Boot Admin Client用于(注销)注册的端点的CSRF-Protection。
                                    new AntPathRequestMatcher(this.adminServer.path("/actuator/**")) // 对执行器端点禁用CSRF-Protection。
                            ))
                    .rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
        }

    }
}

修改Admin Server配置文件,新增如下配置。


spring.security.user.name=admin
spring.security.user.password=admin

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

访问Admin Server,输入账号密码,admin/admin。

在这里插入图片描述

5、邮件通知

Admin Server服务中,添加邮件相关依赖

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

新增相关配置项

spring.mail.host=smtp.qq.com

# to和from都要配置,否则发送邮件时会报错
spring.boot.admin.notify.mail.to=263527944@qq.com
spring.boot.admin.notify.mail.from=263527944@qq.com

# 邮件的用户名和密码
spring.mail.username=263527944@qq.com
spring.mail.password=wmdnczgokxvrcajc

未配置spring.boot.admin.notify.mail.from

org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 501 Mail from address must be same as authorization user.

在这里插入图片描述

账号或密码错误

javax.mail.AuthenticationFailedException: 535 Login Fail. Please enter your authorization code to login

在这里插入图片描述

成功收到服务上下线的邮件

在这里插入图片描述

在这里插入图片描述

5、日志配置

默认情况下,日志文件无法通过执行器端点访问,因此在Spring Boot Admin中不可见。为了启用日志文件执行器端点,您需要通过设置logging.file.path或将Spring Boot配置为写入日志文件 logging.file.name。

新增配置项

# 日志文件路径
logging.file.path=D:\\idea_workspace\\springcloud\\admin\\log
# 文件格式
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

可以动态调整日志级别

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
Spring Boot Admin 是一个开源的管理工具,可以用来监控和管理 Spring Boot 应用程序,提供了一系列功能,如应用程序的状态监控、堆栈跟踪、日志级别控制等。下面是搭建 Spring Boot Admin 的步骤: 1. 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-server</artifactId> <version>2.3.1</version> </dependency> ``` 2. 在启动类上添加注解@EnableAdminServer: ```java @SpringBootApplication @EnableAdminServer public class SpringBootAdminApplication { public static void main(String[] args) { SpringApplication.run(SpringBootAdminApplication.class, args); } } ``` 3. 配置被监控的应用程序,在被监控的应用程序的 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-client</artifactId> <version>2.3.1</version> </dependency> ``` 4. 在被监控的应用程序的配置文件中添加以下配置: ```yaml spring.boot.admin.client.url: http://localhost:8080 spring.boot.admin.client.username: admin spring.boot.admin.client.password: admin ``` 其中,`spring.boot.admin.client.url` 指向 Spring Boot Admin 服务器的地址,`spring.boot.admin.client.username` 和 `spring.boot.admin.client.password` 是访问 Spring Boot Admin 服务器的用户名和密码。 5. 启动 Spring Boot Admin 服务器和被监控的应用程序,访问 http://localhost:8080 即可查看被监控的应用程序的状态信息。 以上就是搭建 Spring Boot Admin 的简单步骤,希望能对你有所帮助。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码拉松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值