Chao's Blog Chao's Blog
首页
  • vue

    • vue路由
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • java
  • spring
  • springboot
  • springcloud
  • git
  • maven
  • nginx
  • tomcat
  • springmvc
  • jvm
  • 图数据库
  • mysql数据库
  • redis数据库
  • windows下docker安装nginx并挂载目录
  • linux命令
  • linux安装软件
  • linux脚本
  • idea
  • vscode
  • 归档
  • 综合项目

    • 若依项目
    • mall项目
  • java
  • mybatis
  • xxl-job
  • mybatis
GitHub (opens new window)

~chao

永远菜鸟,不断努力~
首页
  • vue

    • vue路由
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • java
  • spring
  • springboot
  • springcloud
  • git
  • maven
  • nginx
  • tomcat
  • springmvc
  • jvm
  • 图数据库
  • mysql数据库
  • redis数据库
  • windows下docker安装nginx并挂载目录
  • linux命令
  • linux安装软件
  • linux脚本
  • idea
  • vscode
  • 归档
  • 综合项目

    • 若依项目
    • mall项目
  • java
  • mybatis
  • xxl-job
  • mybatis
GitHub (opens new window)
  • java

  • spring

  • springboot

    • springboot注解
    • aop低版本方法内调用方法捕获不到的解决办法
    • springboot 后端解决跨域问题
    • springboot 整合seata
    • springboot的核心注解
    • Spring boot admin 安全配置(非注册中心模式)
    • Nacos和Email整合Spring Boot Admin
      • springboot通过接口重新加载某个bean
    • springcloud

    • git

    • maven

    • nginx

    • tomcat

    • springmvc

    • jvm

    • 正则表达式

    • 消息中间件

    • python

    • 后端
    • springboot
    ~chao
    2022-11-14
    目录

    Nacos和Email整合Spring Boot Admin

    #

    # 1. 什么是Spring Boot Admin

    gitHub (opens new window)
    springboot 有一个非常好用的监控和管理的源软件,这个软件就是spring boot admin,该软件能够将Actuator中的信息进行图形化的展示,也可以监控 Spring Boot 应用的健康状况,提供实时报警功能.
    主要的功能点有

    • 显示应用程序的监控状态
    • 应用程序上下线监控
    • 查看JVM,线程信息
    • 可视化的查看日志以及下载日志文件
    • 动态切换日志级别
    • http请求信息跟踪
    • 其他功能点...

    # 2. 服务端

    # 2.1 设置Spring Boot Admin Server
    <dependencies>
            <!-- 注册进nacos -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            </dependency>
            <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-starter-server</artifactId>
                <version>2.3.0</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--监控-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            
            <!--整合权限账号 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
    
        </dependencies>
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29

    设置启动类

    /**
     * @PROJECT_NAME: 杭州品茗信息技术有限公司
     * @DESCRIPTION:
     * @author: 徐子木
     * @DATE: 2021/1/4 9:24 上午
     */
    @EnableAdminServer
    @EnableDiscoveryClient
    @SpringBootApplication
    public class MainBootAdmin {
    
        public static void main(String[] args) {
            SpringApplication.run(MainBootAdmin.class,args);
        }
    
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    bootstrap.yml注册到nacos(配置nacos地址,开启actuator全部端点,配置日志打印路径)

    spring:
      application:
        name: boot-admin
      cloud:
        nacos:
          discovery:
            server-addr: 192.168.10.37:18848
            namespace: 77613cbe-9303-4d79-983e-8e5aef69cc45
            group: PM_DEV
            
    management:
      endpoints:
        web:
          exposure:
            include: '*'
      endpoint:
        health:
          show-details: always
    
    logging:
      file: /home/java/admin.log
            
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22

    添加配置

      cloud:
        nacos:
          discovery:
            server-addr: 192.168.10.37:18848
            namespace: 77613cbe-9303-4d79-983e-8e5aef69cc45
            group: PM_DEV
            metadata:
              user.name: "admin"
              user.password: "pinming9158"
      security:
        user:
          name: "admin"
          password: "pinming9158"
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

    编写Security的配置

    package com.zimu.boot.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;
    import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
    
    /**
     * @PROJECT_NAME: 杭州品茗信息技术有限公司
     * @DESCRIPTION:
     * @author: 徐子木
     * @DATE: 2021/1/4 4:26 下午
     */
    @Configuration
    public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
    
        private final String adminContextPath;
    
        public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
            this.adminContextPath = adminServerProperties.getContextPath();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // 登录成功处理类
            SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
            successHandler.setTargetUrlParameter("redirectTo");
            successHandler.setDefaultTargetUrl(adminContextPath + "/");
    
            http.authorizeRequests()
                    //静态文件允许访问
                    .antMatchers(adminContextPath + "/assets/**").permitAll()
                    //登录页面允许访问
                    .antMatchers(adminContextPath + "/login","/css/**","/js/**","/image/*").permitAll()
                    //其他所有请求需要登录
                    .anyRequest().authenticated()
                    .and()
                    //登录页面配置,用于替换security默认页面
                    .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
                    //登出页面配置,用于替换security默认页面
                    .logout().logoutUrl(adminContextPath + "/logout").and()
                    .httpBasic().and()
                    .csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                    .ignoringAntMatchers(
                            "/instances",
                            "/actuator/**"
                    );
    
        }
    
    
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55

    启动项目,即可看到登录页面,输入配置的账号密码登录,能看到注册的服务

    image.png
    image.png

    # 2.2 跨域影响

    由于Spring Admin Server UI 里有很多js和css,在我们上生产时,大多数选择nginx代理加重定向头的组合,这会是页面加载崩溃,找不到元素,所以我们要配置nginx代理的proxy_set_header 以及服务端跨域处理

    location ^~ /control/ {
        proxy_pass http://192.168.10.37:7979;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto https;
    }
    
    
    1
    2
    3
    4
    5
    6
    package com.zimu.boot.config;
    
    import de.codecentric.boot.admin.server.config.AdminServerProperties;
    import org.apache.catalina.valves.RemoteIpValve;
    import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
    import org.springframework.context.annotation.Bean;
    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;
    import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.List;
    
    
    /**
     * @PROJECT_NAME: 杭州品茗信息技术有限公司
     * @DESCRIPTION:
     * @author: 徐子木
     * @DATE: 2021/1/4 4:30 下午
     */
    @Configuration
    public class CorsConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowCredentials(true)
                    .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
                    .allowedHeaders("origin", "content-type", "accept", "x-requested-with")
                    .maxAge(3600);
        }
    
        private CorsConfiguration buildConfig() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            List<String> list = new ArrayList<>();
            list.add("*");
            corsConfiguration.setAllowedOrigins(list);
    
            corsConfiguration.addAllowedOrigin("*");
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
    
            return corsConfiguration;
        }
    
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", buildConfig());
            return new CorsFilter(source);
        }
    
        @Bean
        public TomcatServletWebServerFactory servletContainer(){
            TomcatServletWebServerFactory  factory = new TomcatServletWebServerFactory ();
            factory.setUriEncoding(Charset.forName("UTF-8"));
            RemoteIpValve value = new RemoteIpValve();
            value.setRemoteIpHeader("X-Forwarded-For");
            value.setProtocolHeader("X-Forwarded-Proto");
            value.setProtocolHeaderHttpsValue("https");
            factory.addEngineValves(value);
            return factory;
        }
    
    
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    # 2.3 报警邮件

    在我们服务宕机或上线时可以自动触发邮件发送,需要提前开启邮件的imtp和smtp功能,请自行了解

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-mail</artifactId>
            </dependency>
    
    1
    2
    3
    4
      boot:
        admin:
          context-path: "control"
          notify:
            mail:
              to: [email protected] # 发送给
              from: [email protected] #发送者
      mail:
        default-encoding: UTF-8
        host:   #邮件服务器
        username:    ##用户名
        password:  #密码
        properties:
          mail:
            debug: false
            smtp:
              port: 465
              auth: true
              ssl:
                enable: true
                socket-factory: sf
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21

    # 3. 客户端注册

           <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-starter-client</artifactId>
                <version>2.3.0</version>
            </dependency>
            
            <!--监控-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            </dependency>
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    启动类
    client端相对简单,因为nacos自动帮我们整合了与admin的关联工作,只需要注册进nacos,并且与服务端保持在同一命名空间和分组下即可
    bootstrap.yml

      cloud:
        nacos:
          discovery:
            server-addr: 192.168.10.37:18848
            namespace: 77613cbe-9303-4d79-983e-8e5aef69cc45
            group: PM_DEV
            metadata:
              management:
    
    management:
      health:
        redis:
          enabled: false
        sentinel:
          enabled: false
        ldap:
          enabled: false
      endpoints:
        web:
          exposure:
            include: "*"
      endpoint:
        health:
          show-details: always
    
    logging:
      file:
      
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    编辑 (opens new window)
    上次更新: 2024/01/26, 05:03:22
    Spring boot admin 安全配置(非注册中心模式)
    springboot通过接口重新加载某个bean

    ← Spring boot admin 安全配置(非注册中心模式) springboot通过接口重新加载某个bean→

    最近更新
    01
    python使用生成器读取大文件-500g
    09-24
    02
    Windows环境下 Docker Desktop 安装 Nginx
    04-10
    03
    使用nginx部署多个前端项目(三种方式)
    04-10
    更多文章>
    Theme by Vdoing | Copyright © 2022-2024 chaos | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式