官方指标监控神器SpringBootAdmin保姆级教程

发布于:2022-08-09 ⋅ 阅读:(698) ⋅ 点赞:(0)

SpringBoot Admin

在这里插入图片描述

概述

Spring Boot 有一个非常好用的监控和管理的源软件,这个软件就是 Spring Boot Admin。该软件能够将 Actuator 中的信息进行界面化的展示,也可以监控所有 Spring Boot 应用的健康状况,提供实时警报功能。

主要的功能点有:

  • 显示应用程序的监控状态
  • 应用程序上下线监控
  • 查看 JVM,线程信息
  • 可视化的查看日志以及下载日志文件
  • 动态切换日志级别
  • Http 请求信息跟踪
  • 其他功能点……
  • 可点击 https://github.com/codecentric/spring-boot-admin 更多了解 Spring-boot-admin。

1.搭建Admin服务器

创建建对应的SpringBoot项目,添加相关依赖

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

版本说明:版本建议: Spring Boot 2.x=Spring Boot Admin 2.x (比如Spring Boot 2.3.x 可以用Spring Boot Admin 2.3.x)

然后放开Admin服务即可

img

然后启动服务,即可访问

img

这个时候没有服务注册,所以是空的,这时我们可以创建对应的客户端来监控

2.客户端配置

创建一个SpringBoot项目整合Actuator后添加Admin的客户端依赖

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

然后在属性文件中添加服务端的配置和Actuator的基本配置

server.port=8080
# 配置 SpringBoot Admin 服务端的地址
spring.boot.admin.client.url=http://localhost:8080
# Actuator的基本配置
management.endpoints.web.exposure.include=*

然后我们再刷新Admin的服务端页面

img

那么我们就可以在这个可视化的界面来处理操作了

img

3.服务状态

我们可以监控下MySQL的状态,先添加对应的依赖

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

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

然后添加对应的jdbc配置

spring.datasource.driverClassName=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/mysql-base?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=truespring.datasource.username=rootspring.datasource.password=123456

然后我们在Admin中的health中就可以看到对应的数据库连接信息

img

注意当我把MySQL数据库关闭后,我们来看看

img

我们可以看到Admin中的应用墙变灰了

imgimg

启动服务后,发现又正常了,然后我们修改下数据库连接的超时时间

# 数据库连接超时时间
spring.datasource.hikari.connection-timeout=2000

关闭数据库后,我们发下应用变红了

imgimg

设置数据库连接超时后即可在有效的时间内发下应用的状态。

  • 绿色:正常状态
  • 灰色:连接客户端健康信息超时
  • 红色:可以看到具体的异常信息

4.安全防护

其实我们可以发现在SpringBootAdmin的管理页面中我们是可以做很多的操作的,这时如果别人知道了对应的访问地址,想想是不是就觉得恐怖,所以必要的安全防护还是很有必要的,我们来看看具体应该怎么来处理呢?

由于在分布式 web 应用程序中有几种解决身份验证和授权的方法,Spring Boot Admin 没有提供默认的方法。默认情况下,spring-boot-admin-server-ui 提供了一个登录页面和一个注销按钮。

导入依赖:

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

然后添加对应的配置类

package com.bobo.admin.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;

@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())
                .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                        .ignoringRequestMatchers(
                                new AntPathRequestMatcher(this.adminServer.path("/instances"),
                                        HttpMethod.POST.toString()),
                                new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
                                        HttpMethod.DELETE.toString()),
                                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.security.user.name=userspring.security.user.password=123456

然后访问Admin管理页面

img

输入账号密码后可以进入,但是没有监控的应用了

imgimage.png

原因是被监控的服务要连接到Admin服务端也是需要认证的

imgimage.png

我们在客户端配置连接的账号密码即可

imgimage.png

重启后访问Admin服务管理页面

img

搞定

5.注册中心

实际开发的时候我们可以需要涉及到的应用非常多,我们也都会把服务注册到注册中心中,比如nacos,Eureka等,接下来我们看看如何通过注册中心来集成客户端。就不需要每个客户端来集成了。

img

变为下面的场景

img

那么我们需要先启动一个注册中心服务,我们以Nacos为例

img

然后访问下Nacos服务

img

admin-server需要添加Nacos的注册中心配置外,我们还需要添加Actuator的配置

img

配置 bootstrap.yml

# Tomcat
server:
  port: 9666

# Spring
spring:
  application:
    # 应用名称
    name: sb-admin
  profiles:
    # 环境配置
    active: @profiles.active@

  security:
    user:
      name: user
      password: 123456
  cloud:
    nacos:
      discovery:
        # 服务注册地址
        server-addr: @nacos.server-addr@
        namespace: @nacos.discovery.namespace@
        username: @nacos.username@
        password: @nacos.password@
        enabled: true
      config:
        # 配置中心地址
        server-addr: @nacos.server-addr@
        # 配置文件格式
        file-extension: yml
        namespace: @nacos.config.namespace@
        username: @nacos.username@
        password: @nacos.password@

然后启动相关的服务,可以看到相关的服务

image-20220805145305103

然后我们需要配置下Admin中的nacos

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.admin4j.common</groupId>
    <artifactId>spring-boot-admin-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-admin-server</name>
    <description>spring-boot-admin-server</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-boot-admin.version>2.3.1</spring-boot-admin.version>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.7.RELEASE</spring-cloud-alibaba.version>
    </properties>
    <dependencies>
        <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>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-dependencies</artifactId>
                <version>${spring-boot-admin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- SpringCloud 微服务 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>app</finalName>
        <!--  编译资源-->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>dev</id>
            <properties>
                <!--开发环境-->
                <profiles.active>dev</profiles.active>
                <nacos.server-addr>192.168.1.12:8848</nacos.server-addr>
                <nacos.username>nacos</nacos.username>
                <nacos.password>nacos</nacos.password>
                <nacos.config.namespace>fb1eb62c-f7ad-41cc-acba-16b60073c65e</nacos.config.namespace>
                <nacos.discovery.namespace>b0ad0965-c5dd-441c-ad49-2136f74a94cb</nacos.discovery.namespace>
                <nacos.group>DEFAULT_GROUP</nacos.group>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
    </profiles>

</project>

启动服务,我们就可以看到对应的服务了

image-20220805145359775

要查看服务的详细监控信息,我们需要配置对应的Actuator属性

imgimage.pngimage-20220805145422354

好了注册中心处理这块就介绍到这里

6.邮件通知

如果监控的服务出现了问题,下线了,我们希望通过邮箱通知的方式来告诉维护人员,

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

然后配置对应的邮箱信息

# 使用的邮箱服务  qq 163等
spring.mail.host=smtp.qq.com
# 发送者
spring.mail.username=279583842@qq.com
# 授权码
spring.mail.password=rhcqzhfslkwjcach
#收件人
spring.boot.admin.notify.mail.to=1234567898@qq.com
#发件人
spring.boot.admin.notify.mail.from=12345678989@qq.com

img

发送短信开启

img

然后启动服务

img

然后我们关闭服务然后查看服务和邮箱信息

img

image-20220805145613645 img

好了对应的邮箱通知就介绍到这里,其他的通知方式可以参考官方网站

代码地址

https://github.com/andanyoung/spring-boot-admin-server

本文含有隐藏内容,请 开通VIP 后查看