详解用Spring Boot Admin来监控我们的微服务
作者:后端老鸟 发布时间:2022-02-12 15:18:03
1.概述
Spring Boot Admin是一个Web应用程序,用于管理和监视Spring Boot应用程序。每个应用程序都被视为客户端,并注册到管理服务器。底层能力是由Spring Boot Actuator端点提供的。
在本文中,我们将介绍配置Spring Boot Admin服务器的步骤以及应用程序如何集成客户端。
2.管理服务器配置
由于Spring Boot Admin Server可以作为servlet或webflux应用程序运行,根据需要,选择一种并添加相应的Spring Boot Starter。在此示例中,我们使用Servlet Web Starter。
首先,创建一个简单的Spring Boot Web应用程序,并添加以下Maven依赖项:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
之后,@ EnableAdminServer将可用,因此我们将其添加到主类中,如下例所示:
@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminServerApplication.class, args);
}
}
至此,服务端就配置完了。
3.设置客户端
要在Spring Boot Admin Server服务器上注册应用程序,可以包括Spring Boot Admin客户端或使用Spring Cloud Discovery(例如Eureka,Consul等)。
下面的例子使用Spring Boot Admin客户端进行注册,为了保护端点,还需要添加spring-boot-starter-security,添加以下Maven依赖项:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
接下来,我们需要配置客户端说明管理服务器的URL。为此,只需添加以下属性:
spring.boot.admin.client.url=http://localhost:8080
从Spring Boot 2开始,默认情况下不公开运行状况和信息以外的端点,对于生产环境,应该仔细选择要公开的端点。
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
使执行器端点可访问:
@Configuration
public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll()
.and().csrf().disable();
}
}
为了简洁起见,暂时禁用安全性。
如果项目中已经使用了Spring Cloud Discovery,则不需要Spring Boot Admin客户端。只需将DiscoveryClient添加到Spring Boot Admin Server,其余的自动配置完成。
下面使用Eureka做例子,但也支持其他Spring Cloud Discovery方案。
将spring-cloud-starter-eureka添加到依赖中:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
通过添加@EnableDiscoveryClient到配置中来启用发现
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
@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();
}
}
}
配置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
4.安全配置
Spring Boot Admin服务器可以访问应用程序的敏感端点,因此建议为admin 服务和客户端应用程序添加一些安全配置。
由于有多种方法可以解决分布式Web应用程序中的身份验证和授权,因此Spring Boot Admin不会提供默认方法。默认情况下spring-boot-admin-server-ui提供登录页面和注销按钮。
服务器的Spring Security配置如下所示:
@Configuration(proxyBeanMethods = false)
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()),
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));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER");
}
}
添加之后,客户端无法再向服务器注册。为了向服务器注册客户端,必须在客户端的属性文件中添加更多配置:
spring.boot.admin.client.username=admin
spring.boot.admin.client.password=admin
当使用HTTP Basic身份验证保护执行器端点时,Spring Boot Admin Server需要凭据才能访问它们。可以在注册应用程序时在元数据中提交凭据。在BasicAuthHttpHeaderProvider随后使用该元数据添加Authorization头信息来访问应用程序的执行端点。也可以提供自己的属性HttpHeadersProvider来更改行为(例如添加一些解密)或添加额外的请求头信息。
使用Spring Boot Admin客户端提交凭据:
spring.boot.admin.client:
url: http://localhost:8080
instance:
metadata:
user.name: ${spring.security.user.name}
user.password: ${spring.security.user.password}
使用Eureka提交凭据:
eureka:
instance:
metadata-map:
user.name: ${spring.security.user.name}
user.password: ${spring.security.user.password}
5.日志文件查看器
默认情况下,日志文件无法通过执行器端点访问,因此在Spring Boot Admin中不可见。为了启用日志文件执行器端点,需要通过设置logging.file.path或将Spring Boot配置为写入日志文件 logging.file.name。
Spring Boot Admin将检测所有看起来像URL的内容,并将其呈现为超链接。
还支持ANSI颜色转义。因为Spring Boot的默认格式不使用颜色,可以设置一个自定义日志格式支持颜色。
logging.file.name=/var/log/sample-boot-application.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
6. 通知事项
邮件通知
邮件通知将作为使用Thymeleaf模板呈现的HTML电子邮件进行传递。要启用邮件通知,请配置JavaMailSender使用spring-boot-starter-mail并设置收件人。
将spring-boot-starter-mail添加到依赖项中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置一个JavaMailSender
spring.mail.username=smtp_user
spring.mail.password=smtp_password
spring.boot.admin.notify.mail.to=admin@example.com
无论何时注册客户端将其状态从“ UP”更改为“ OFFLINE”,都会将电子邮件发送到上面配置的地址。
自定义通知程序
可以通过添加实现Notifier接口的Spring Bean来添加自己的通知程序,最好通过扩展 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());
}
});
}
}
其他的一些配置参数和属性可以通过官方文档来了解。
来源:https://blog.csdn.net/huahao1989/article/details/108039738
猜你喜欢
- 本文实例为大家分享了JAVA NIO实现简单聊天室功能的具体代码,供大家参考,具体内容如下服务端初始化一个ServerSocketChann
- 本文研究的主要是Hibernate hql查询的相关内容,具体如下。HQL介绍Hibernate语言查询(Hibernate Query L
- 本文实例讲述了java实现简单的英文文本单词翻译器功能。分享给大家供大家参考,具体如下:直接上代码:package fanyi;import
- 1、导入资源2、JSP代码<div class="page-container">  
- 文档更新说明2018年09月24日 v1.0 初稿代理在生活中很常见,比如说婚介网站,其实就是找对象的代理;还有社保代理、人事代理;还有找黄
- makeCertPic.javapackage pic;import java.awt.Color;import java.awt.Font
- 本文实例讲述了Java基于享元模式实现五子棋游戏功能。分享给大家供大家参考,具体如下:一、模式定义享元模式,以共享的方式高效地支持大量的细粒
- 众所周知Java中的数据类型是强数据类型,基本数据类型之间的转换尤其固定的规则,当数据宽度比较窄的数据类型(如int)转换成数据类型比较宽的
- package com.wanmei.meishu;import java.io.FileInputStream;import java.i
- 当使用spring-Boot时,嵌入式Servlet容器通过扫描注解的方式注册Servlet、Filter和Servlet规范的所有 * (
- 本文实例为大家分享了Java图片验证码代码,供大家参考,具体内容如下网页显示效果:index.jsp 使用两种方式强制图片更新: 1、设置图
- 环境:Spring5.3.12.RELEASE。Spring 3引入了一个core.onvert包,提供一个通用类型转换系统。系统定义了一个
- 一、CORS概述跨源资源共享标准通过新增一系列 HTTP 头,让服务器能声明那些来源可以通过浏览器访问该服务器上的各类资源(包括CSS、图片
- 前言Spring框架中的BeanFactory接口和FactoryBean接口因为名称相似,老是容易搞混淆,而且也是面试过程中经常会碰到的一
- 把做工程过程常用的一些代码段做个记录,下面代码是关于Java实现图片倒影的的代码,应该对大家有较大用处。 public class
- 选择排序:(Selection sort)是一种简单直观的排序算法,也是一种不稳定的排序方法。选择排序的原理一组无序待排数组,做升序排序,我
- JFormDesigner概述jformdesigner是一款功能强大的Swing设计工具,这是全面的程序,可帮助您创建Swing GUI,
- 概述不知道大家在平时的开发过程中或者源码里是否留意过内部类,那有思考过为什么要有内部类,内部类都有哪几种形式,静态内部类和普通内部类有什么区
- 在C#的List集合操作中,有时候需要查找到List集合中的最大值,此时可以使用List集合的扩展方法Max方法,Max方法有2种形式,一种
- 如何给请求添加header背景:在集成了swagger的项目中,调用后台接口往往会经过一些自定义的 * ,而 * 加了token限制的话,直