用Spring Boot Admin来监控我们的微服务

本文涉及的产品
云原生网关 MSE Higress,422元/月
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
MSE Nacos/ZooKeeper 企业版试用,1600元额度,限量50份
简介: Spring Boot Admin是一个Web应用程序,用于管理和监视Spring Boot应用程序。每个应用程序都被视为客户端,并注册到管理服务器。底层能力是由Spring Boot Actuator端点提供的。

【转载请注明出处】:https://blog.csdn.net/huahao1989/article/details/108039738

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

}

其他的一些配置参数和属性可以通过官方文档来了解。

欢迎关注 “后端老鸟” 公众号,接下来会发一系列的专题文章,包括Java、Python、Linux、SpringBoot、SpringCloud、Dubbo、算法、技术团队的管理等,还有各种脑图和学习资料,NFC技术、搜索技术、爬虫技术、推荐技术、音视频互动直播等,只要有时间我就会整理分享,敬请期待,现成的笔记、脑图和学习资料如果大家有需求也可以公众号留言提前获取。由于本人在所有团队中基本都处于攻坚和探路的角色,搞过的东西多,遇到的坑多,解决的问题也很多,欢迎大家加公众号进群一起交流学习。

【转载请注明出处】:https://blog.csdn.net/huahao1989/article/details/108039738

image

相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
相关文章
|
27天前
|
负载均衡 Java API
《深入理解Spring》Spring Cloud 构建分布式系统的微服务全家桶
Spring Cloud为微服务架构提供一站式解决方案,涵盖服务注册、配置管理、负载均衡、熔断限流等核心功能,助力开发者构建高可用、易扩展的分布式系统,并持续向云原生演进。
|
2月前
|
Prometheus 监控 Java
日志收集和Spring 微服务监控的最佳实践
在微服务架构中,日志记录与监控对系统稳定性、问题排查和性能优化至关重要。本文介绍了在 Spring 微服务中实现高效日志记录与监控的最佳实践,涵盖日志级别选择、结构化日志、集中记录、服务ID跟踪、上下文信息添加、日志轮转,以及使用 Spring Boot Actuator、Micrometer、Prometheus、Grafana、ELK 堆栈等工具进行监控与可视化。通过这些方法,可提升系统的可观测性与运维效率。
255 1
日志收集和Spring 微服务监控的最佳实践
|
2月前
|
监控 Java 数据库
从零学 Dropwizard:手把手搭轻量 Java 微服务,告别 Spring 臃肿
Dropwizard 整合 Jetty、Jersey 等成熟组件,开箱即用,无需复杂配置。轻量高效,启动快,资源占用少,内置监控、健康检查与安全防护,搭配 Docker 部署便捷,是构建生产级 Java 微服务的极简利器。
230 2
|
3月前
|
存储 Prometheus 监控
从入门到实战:一文掌握微服务监控系统 Prometheus + Grafana
随着微服务架构的发展,系统监控变得愈发重要。本文介绍如何利用 Prometheus 和 Grafana 构建高效的监控系统,涵盖数据采集、存储、可视化与告警机制,帮助开发者提升系统可观测性,及时发现故障并优化性能。内容涵盖 Prometheus 的核心组件、数据模型及部署方案,并结合 Grafana 实现可视化监控,适合初学者和进阶开发者参考实践。
497 6
|
2月前
|
监控 Kubernetes Java
使用 New Relic APM 和 Kubernetes Metrics 监控 EKS 上的 Java 微服务
在阿里云AKS上运行Java微服务常遇性能瓶颈与OOMKilled等问题。本文教你通过New Relic实现集群与JVM双层监控,集成Helm部署、JVM代理注入、GC调优及告警仪表盘,打通从节点资源到应用内存的全链路观测,提升排障效率,保障服务稳定。
169 1
|
4月前
|
存储 监控 Shell
SkyWalking微服务监控部署与优化全攻略
综上所述,虽然SkyWalking的初始部署流程相对复杂,但通过一步步的准备和配置,可以充分发挥其作为可观测平台的强大功能,实现对微服务架构的高效监控和治理。尽管未亲临,心已向往。将一件事做到极致,便是天分的展现。
|
5月前
|
Prometheus 监控 Cloud Native
|
5月前
|
Prometheus 监控 Cloud Native
Spring Boot 可视化监控
本文介绍了如何通过Spring Actuator、Micrometer、Prometheus和Grafana为Spring Boot应用程序添加监控功能。首先创建了一个Spring Boot应用,并配置了Spring Actuator以暴露健康状态和指标接口。接着,利用Micrometer收集应用性能数据,并通过Prometheus抓取这些数据进行存储。最后,使用Grafana将Prometheus中的数据可视化,展示在精美的仪表板上。整个过程简单易行,为Spring Boot应用提供了基本的监控能力,同时也为后续扩展更详细的监控指标奠定了基础。
899 2
|
4月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
834 0

热门文章

最新文章