首页 > 其他分享 >Spring Boot Admin 入门

Spring Boot Admin 入门

时间:2022-11-15 10:46:14浏览次数:65  
标签:spring Admin Spring boot springframework admin Boot org import

Spring Boot Admin 入门

Spring Boot Admin 是一个社区项目,主要用于管理和监控 SpringBoot 应用程序

搭建 Spring Boot Admin 服务器

1、创建 springboot 项目,引入以下依赖:

<!--2.7.7版本没有 @EnableAdminServer 注解-->
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.6.1</version>
</dependency>

spring-boot-admin-starter-server 的版本建议和 spring-boot-starter-parent 的版本保持一致

2、启动类添加注解 @EnableAdminServer,eg:

package com.yl;

import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author YL
 */
@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminTestApplication {

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

}

3、配置文件

server:
  port: 8071

spring:
  application:
    name: admin-server

至此,可以启动项目访问:http://127.0.0.1:8071 进入监控页面

注册 Spring Boot Admin 客户端

1、创建 springboot 项目,引入以下依赖:

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

2、配置文件

server:
  port: 8091

spring:
  application:
    name: admin-client01
  boot:
    admin:
      client:
        # admin 服务端地址,不配置也可以监控,建议配置
        url: http://127.0.0.1:8071

management:
  endpoint:
    health:
      # 显示健康信息
      show-details: always
  endpoints:
    web:
      exposure:
        # 开放所有端点访问权限
        include: "*"

再次访问监控页面即可看到客户端相关数据

整合 spring security

1、服务端引入以下依赖:

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

2、创建 spring security 配置类

package com.yl.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
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;

/**
 * security config 配置
 *
 * @author YL
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final String adminContextPath;

    public SecurityConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");

        http.authorizeRequests()
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler)
                .and()
                .logout().logoutUrl(adminContextPath + "/logout")
                .and()
                .httpBasic()
                .and()
                .csrf().disable();
    }

}

3、服务端配置用户名和密码,在 application.yml 配置文件中添加以下配置:

spring:
  security:
    user:
      name: admin
      password: admin123

4、客户端配置用户名和密码,在 application.yml 配置文件中添加以下配置:

spring:
  boot:
    admin:
      client:
        # admin 服务端用户名
        username: admin
        # admin 服务端密码
        password: admin123

如果客户端不配置对应的用户名和密码将不会被服务端监控

再次访问,需要填写用户名和密码登录后才能看到监控数据

邮件配置

客户端离线,出现故障的时候,能发送邮件及时通知

1、服务端引入以下依赖:

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

2、服务端配置邮件相关信息,在 application.yml 配置文件中添加以下配置:

spring:
  boot:
    admin:
      notify:
        mail:
          enabled: true
          # 发件人
          from: [email protected]
          # 收件人,多个中间用,分隔
          to: [email protected]
  mail:
    # 发件人使用的 qq 邮箱服务
    host: smtp.qq.com
    username: [email protected]
    # 授权码不是密码,在 qq 邮箱设置‐账号里面有生成授权码
    password: ghchqentbyzkdbfc

授权码在 qq 邮箱-设置-账户里边 点击按钮可以获取:

配置成功之后,启动服务端,再启动客户端,然后停掉客户端,等待片刻,看是否会有邮件发送,如果收到那么就是配置成功了

日志文件配置

在客户端配置文件添加以下配置:

logging:
  file:
    # 路径可自定义
    name: D:\IdeaProject\sample-boot-application.log
  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"

重启客户端即可看到相关日志:

自定义 info 端点信息

info 端点描述了当前应用的基本信息,可以通过两种形式快速配置 info 端点的信息

  • 配置文件形式,在客户端 application.yml 添加如下配置:
management:
  info:
    env:
      # 打开 info 配置
      enabled: true

# info 配置信息
info:
  author: YL
  version: 1.0
  • 编程形式,在客户端增加如下配置类:
package com.yl.config;

import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Spring Boot Admin info 配置
 *
 * @author YL
 */
@Component
public class InfoConfig implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        // 添加单个信息
        builder.withDetail("runTime", new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()));

        Map infoMap = new HashMap(16);
        infoMap.put("buildTime", "2022-11-15");
        // 添加一组信息
        builder.withDetails(infoMap);
    }

}

配置完成后重启客户端,可以看到如下信息:

自定义 Health 端点指标

health 端点描述当前应用的运行健康指标,即应用的运行是否成功,通过编程的形式可以扩展指标信息,eg:

package com.yl.config;

import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Spring Boot Admin 健康信息配置
 *
 * @author YL
 */
@Component
public class HealthConfig extends AbstractHealthIndicator {

    /**
     * 健康检查
     *
     * @param builder
     */
    @Override
    protected void doHealthCheck(Health.Builder builder) {
        boolean condition = false;
        if (condition) {
            // 设置运行状态为启动状态
            builder.status(Status.UP);
            builder.withDetail("runTime", System.currentTimeMillis());

            Map infoMap = new HashMap(16);
            infoMap.put("buildTime", "2022");
            builder.withDetails(infoMap);
        } else {
            // 设置运行状态为不在服务状态
            builder.status(Status.OUT_OF_SERVICE);
            builder.withDetail("server status", "down");
        }
    }

}
  • 健康检查通过时:

  • 健康检查不通过时:

自定义端点

可以根据业务需要自定义端点,方便业务监控,eg:

package com.yl.endpoint;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Spring Boot Admin 自定义端点
 *
 * @author YL
 */
@Component
@Endpoint(id = "myEndpoint", enableByDefault = true)
public class MyEndPoint {

    @ReadOperation
    public Object getMyEndpoint() {
        Map map = new HashMap(3);
        map.put("data1", "001");
        map.put("data2", "002");
        map.put("data3", "003");
        return map;
    }
}

因为自定义端点数据 spirng boot admin 无法预知该如何展示,所以通过界面无法看到此数据,通过HTTP请求路径可以获取到当前端点的信息,但是需要先开启当前端点对外功能,或者设置当前端点为默认开发的端点

postman 测试请求如下:

参考文档:

git 项目:https://github.com/codecentric/spring-boot-admin

官方文档:https://codecentric.github.io/spring-boot-admin/current/#_what_is_spring_boot_admin

https://blog.csdn.net/weixin_46666822/article/details/124483078

https://blog.csdn.net/zouliping123456/article/details/121977792

https://blog.csdn.net/qq_41971087/article/details/115623172

https://blog.csdn.net/weixin_54040016/article/details/127364978

标签:spring,Admin,Spring,boot,springframework,admin,Boot,org,import
From: https://www.cnblogs.com/Y-wee/p/16891599.html

相关文章

  • 一张图彻底搞懂Spring循环依赖
    1什么是循环依赖?如下图所示:BeanA类依赖了BeanB类,同时BeanB类又依赖了BeanA类。这种依赖关系形成了一个闭环,我们把这种依赖关系就称之为循环依赖。同理,再如下图的情况:......
  • Spring 5系统架构
    Spring5系统架构Spring大约有20个模块,由1300多个不同的文件构成。这些模块可以分为核心容器、AOP和设备支持、数据访问与集成、Web组件、通信报文和集成测试、集成兼容等......
  • Spring&SpringBoot常用注解总结
    title:Spring&SpringBoot常用注解总结date:2022-11-1509:11:45tags:1.@SpringBootApplication这里先单独拎出@SpringBootApplication注解说一下,虽然我们一般不会......
  • Spring版本命名规则
    1常见软件的版本命名常见软件的版本命名举例如下表所示。软件升级过程说明LinuxKernel0.0.11.0.02.6.323.0.18若用X.Y.Z表示,则偶数Y表示稳定版本,奇数Y表示开发版......
  • 记录关于spring事务的两个坑
    一,调用本地方法时,事务不起作用。   原因:事务能生效的原因是spring对事务的对象做了动态代理,这里默认的是用this(目标对象)调用方法,所以没有事务功能。需要拿到事务......
  • 【Java】Springboot + Redis + AOP切面实现字典翻译
     使用案例演示:先开发了一个简单的Demo:普通DTO类注解翻译的字段和翻译来源  在需要翻译的方法上注解@Translate  接口返回结果:  框架思路:1、标记的......
  • 重新认识Spring Boot
    SpringBoot的特性方便的创建可独立运行的Spring应用程序直接内嵌Tomcat、Jetty或Undertow简化了项目的构建配置为Spring及第三方库提供自动配置提供生产级特性无需生成代......
  • Spring--依赖注入:setter注入和构造器注入
    依赖注入:描述了在容器中建立Bean于Bean之间依赖关系的过程setter注入在本来已经在service里面引用了bean的相关方法的基础上,再引用之前已经写过的userDao的对象,即在servi......
  • springAop的实现方式
    AOP的三种实现方式AOP是Spring中继IOC(面向切面编程)后又一十分重要的概念。AOP,即面向切面编程。使用AOP可以实现在不改变原有的业务逻辑的代码的情况下,在系统上增加一些特殊......
  • Spring--Bean的生命周期
    Bean的生命周期对于生命周期来说,每个对象都会有起初的初始化和最后的销毁,Bean也不例外;Bean的生命周期可以简述为:Bean的定义--Bean的初始化--Bean的使用--Bean的销毁所以......