Nacos整合Spring Boot Admin

1. 什么是Spring Boot Admin

gitHub

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

主要的功能点有

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

2. 服务端继承

2.1 设置Spring Boot Admin Server

pom.xml

<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>

设置启动类

/**
 * @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);
    }

}

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
        
2.2 集成Spring security

由于多种方法可以解决分布式Web应用程序中的身份验证和授权,因此SpringBootAdmin不会提供默认方法,默认情况下Spring-boot-admin-server-ui提供了登录页面和注销功能

maven截图.png

添加配置

  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"

编写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/**"
                );

    }


}

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

页面还是挺好看的

2.3 跨域影响

由于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;
}

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


}
2.4 报警邮件

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

pom.xml

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

配置账号

  boot:
    admin:
      context-path: "control"
      notify:
        mail:
          to: 3281707032@qq.com # 发送给
          from: 1440923113@qq.com #发送者
  mail:
    default-encoding: UTF-8
    host:   #邮件服务器
    username:    ##用户名
    password:  #密码
    properties:
      mail:
        debug: false
        smtp:
          port: 465
          auth: true
          ssl:
            enable: true
            socket-factory: sf

手动停止一个服务看下效果,成功发送报警邮件

3. 客户端注册

pom.xml

       <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>

启动类

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:
  

一切就绪就可以在控制台看到我们的服务了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容