Nacos整合Spring Boot Admin

1. 什么是Spring Boot Admin

gitHub

springboot 有一個非常好用的監(jiān)控和管理的源軟件,這個軟件就是spring boot admin,該軟件能夠?qū)ctuator中的信息進(jìn)行圖形化的展示,也可以監(jiān)控 Spring Boot 應(yīng)用的健康狀況,提供實(shí)時報警功能.

主要的功能點(diǎn)有

  • 顯示應(yīng)用程序的監(jiān)控狀態(tài)
  • 應(yīng)用程序上下線監(jiān)控
  • 查看JVM,線程信息
  • 可視化的查看日志以及下載日志文件
  • 動態(tài)切換日志級別
  • http請求信息跟蹤
  • 其他功能點(diǎn)...

2. 服務(wù)端繼承

2.1 設(shè)置Spring Boot Admin Server

pom.xml

<dependencies>
        <!-- 注冊進(jìn)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>
        <!--監(jiān)控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        
        <!--整合權(quán)限賬號 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

    </dependencies>

設(shè)置啟動類

/**
 * @PROJECT_NAME: 杭州品茗信息技術(shù)有限公司
 * @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全部端點(diǎn),配置日志打印路徑)

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應(yīng)用程序中的身份驗(yàn)證和授權(quán),因此SpringBootAdmin不會提供默認(rèn)方法,默認(rèn)情況下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: 杭州品茗信息技術(shù)有限公司
 * @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()
                //靜態(tài)文件允許訪問
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                //登錄頁面允許訪問
                .antMatchers(adminContextPath + "/login","/css/**","/js/**","/image/*").permitAll()
                //其他所有請求需要登錄
                .anyRequest().authenticated()
                .and()
                //登錄頁面配置,用于替換security默認(rèn)頁面
                .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
                //登出頁面配置,用于替換security默認(rèn)頁面
                .logout().logoutUrl(adminContextPath + "/logout").and()
                .httpBasic().and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers(
                        "/instances",
                        "/actuator/**"
                );

    }


}

啟動項目,即可看到登錄頁面,輸入配置的賬號密碼登錄,能看到注冊的服務(wù)

頁面還是挺好看的

2.3 跨域影響

由于Spring Admin Server UI 里有很多js和css,在我們上生產(chǎn)時,大多數(shù)選擇nginx代理加重定向頭的組合,這會是頁面加載崩潰,找不到元素,所以我們要配置nginx代理的proxy_set_header 以及服務(wù)端跨域處理

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: 杭州品茗信息技術(shù)有限公司
 * @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 報警郵件

在我們服務(wù)宕機(jī)或上線時可以自動觸發(fā)郵件發(fā)送,需要提前開啟郵件的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 # 發(fā)送給
          from: 1440923113@qq.com #發(fā)送者
  mail:
    default-encoding: UTF-8
    host:   #郵件服務(wù)器
    username:    ##用戶名
    password:  #密碼
    properties:
      mail:
        debug: false
        smtp:
          port: 465
          auth: true
          ssl:
            enable: true
            socket-factory: sf

手動停止一個服務(wù)看下效果,成功發(fā)送報警郵件

3. 客戶端注冊

pom.xml

       <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.3.0</version>
        </dependency>
        
        <!--監(jiān)控-->
        <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端相對簡單,因?yàn)閚acos自動幫我們整合了與admin的關(guān)聯(lián)工作,只需要注冊進(jìn)nacos,并且與服務(wù)端保持在同一命名空間和分組下即可

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:
  

一切就緒就可以在控制臺看到我們的服務(wù)了

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容