SpringBoot入坑指南之四:使用Spring Boot Admin進行服務監控

開篇

說個笑話:「你的代碼沒有Bug!」。 誰也不能保證本身的代碼沒有Bug,本身的代碼可以100%知足業務性能要求,當線上的服務出問題後,如何快速定位問題、解決問題,這纔是一個好程序猿的標誌。 通俗一點說,就是快速地將本身挖的坑填平,最好沒有其餘人發現。html

Spring Boot的服務監控

Spring Boot Actuator

Spring Boot開發之初已經充分考慮服務監控需求,提供了spring-boot-starter-actuator監控模塊,在項目用依賴該模塊就能夠開啓相應的監控endpoit。vue

經常使用的endpoit包括如下:git

endpoints 說明
beans 全部的Spring Bean信息
health 應用健康信息
metrics 應用各方面性能指標
mappings 應用全部的Request Mapping路徑
heapdump 下載內存快照

具體可參考 官方文檔web

Spring Boot Admin

目前經常使用Spring Boot Admin進行Spring Boot應用服務監控,它提供了一個簡潔美觀的監控頁面,底層基於Spring Boot Actuator實現。 Spring Boot Admin包括客戶端和服務端:spring

  • 客戶端:即需監控的應用服務,依賴Spring Boot Admin客戶端包,向服務端進行註冊。
  • 服務端:提供服務端註冊相關服務以及服務監控相關服務,2.0的UI頁面使用vuejs開發。

實現示例

搭建服務端

  • 建立一個spring-boot-examples-admin-server項目,添加如下依賴:
<dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
  • 新增一個配置類SecuritySecureConfig,基於Spring Security實現Admin Server的安全控制,參考代碼以下:
/**
 * @author: cent
 * @email: 292462859@qq.com
 * @date: 2019/2/11.
 * @description: <p>
 * Security配置類,用於配置admin server的安全控制
 */
@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").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/**"
                );
    }
}
  • 建立應用啓動類,在類添加註解@EnableAdminServer啓用Admin Server。
/**
 * @author: cent
 * @email: 292462859@qq.com
 * @date: 2019/2/11.
 * @description:
 */
@EnableAdminServer
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • 配置文件application.yml以下:
spring:
  application:
    name: spring-boot-examples-admin-server
  security:
    user:
      name: admin
      password: 123456

server:
  port: 8090

搭建客戶端

  • 建立一個需監控的Spring Boot應用項目spring-boot-examples-admin-client,添加如下依賴:
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
        </dependency>
  • 建立一個SecuritySecureConfig,實現Security相關邏輯,代碼以下文: 因爲Spring Boot Actuator模塊自身並無安全控制,若是不增長安全控制會存在安全風險,因此使用Spring Security模塊實現安全控制,如下代碼實現對actuator的endpoints進行安全校驗攔截,其餘訪問則不攔截。需注意角色名ACTUATOR_ADMIN,後續配置需使用。
/**
 * @author: cent
 * @email: 292462859@qq.com
 * @date: 2019/2/11.
 * @description:
 */
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //攔截全部endpoint,擁有ACTUATOR_ADMIN角色可訪問,不然需登陸
                .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ACTUATOR_ADMIN")
                //靜態文件容許訪問
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                //根路徑容許訪問
                .antMatchers("/").permitAll()
                //全部請求路徑能夠訪問
                .antMatchers("/**").permitAll()
                .and().httpBasic();
    }
}
  • 應用配置文件application.yml配置以下(具體配置項做用見註釋):
spring:
  application:
    name: spring-boot-examples-admin-client
  boot:
    admin:
      client:
        url: "http://localhost:8090/" #spring admin server訪問地址
        username: admin #spring admin server用戶名
        password: 123456 #spring admin server密碼
        instance:
          metadata:
            user.name: ${spring.security.user.name} #客戶端元數據訪問用戶
            user.password: ${spring.boot.admin.client.password} #客戶端元數據訪問密碼
  security:
    user:
      name: client #客戶端用戶名
      password: 123456 # 客戶端密碼
      roles: ACTUATOR_ADMIN #擁有角色,用於容許自身訪問

# 開放全部endpoint,實際生產根據自身須要開放,出於安全考慮不建議所有開放。
management:
  endpoints:
    web:
      exposure:
        include: "*"

logging:
  path: logs/
  file: admin-client

server:
  port: 8091

啓動演示

  • 分別啓動spring-boot-examples-admin-server和spring-boot-examples-admin-client。安全

  • 訪問http://localhost:8090,可看到登陸頁面。 登陸頁面app

  • 登陸成功後,application頁面。 applicationide

  • Wallboard頁面。 image.pngspring-boot

  • 應用監控詳情頁面 wallboard01 wallboard02性能

參考源碼

碼雲:https://gitee.com/centy/spring-boot-examples

尾巴

Spring Boot Admin使用在Spring Cloud中使用時,能夠與Eureka結合在一塊兒使用,Spring Boot Admin能夠經過Eureka發現其它註冊到Eureka中的服務。

相關文章
相關標籤/搜索