Spring boot 2: use spring boot admin to monitor your application

Time:2020-2-22

Spring boot 2: use spring boot admin to monitor your application

1. Preface

Production pairsWebApplication monitoring is very necessary. We can monitor application health, performance and other indicators in near real time to deal with some emergencies in time. Avoid some faults. aboutSpring BootIn terms of application, we can use a lightweight monitoring toolSpring Boot Admin (SBA)To monitor.

2. Spring Boot Admin

Spring Boot AdminGerman Software EngineerJohannes EdmeierOpen source for management and monitoringSpring BootApplication. The latest official version of spring initializr as of the time of issue is2.1.6Snapshot is2.2.0-SNAPSHOTC/SArchitectural style. Application asSpring Boot Admin ClienttowardsSpring Boot Admin ServerRegistration (viaHTTPOr useSpring CloudRegistration Center (e.gEurekaConsulFound. Server program adopts responsive Web FrameworkSpring Webflux。 Display UI adoptsVue.js, showing some monitoring of spring boot admin client through spring boot activator endpoint. Common functions or monitoring are as follows:

  • Show health
  • Display the application metrics details, such as

    • JVM and memory metrics
    • Micrometer measurement
    • Data source indicators
    • Cache index
  • Show build information number
  • Follow and download log files
  • downloadheapdump
  • SeejvmSystem and environment properties
  • SeeSpring BootConfiguration properties
  • SupportSpring CloudEnvironment endpoint and refresh endpoint for“
  • Support K8s
  • Easy to use log level management
  • AndJMX-beansinteractive
  • View thread dump
  • SeehttpTrack
  • Seeauditevents
  • Seehttp-endpoints
  • View scheduled tasks
  • View and delete active sessions (usingSpring Session
  • SeeFlyway/LiquibaseDatabase migration
  • Notification of status change (via email, slack, hipchat, etc., support pin)
  • Event log for state changes (non persistent)

3. Rapid integration

Next let’s go toSpring BootIntegration in the projectSpring Boot Admin。 Note the compatibility of the version, which can be verified by spring initializr.

3.1 configure spring boot admin server

Spring Boot Admin ServerGenerally recommended as an independentSpring Boot jarApplication running. Just add the following dependencies to yourpom.xmlChina:

<dependency>
     <groupId>de.codecentric</groupId>
     <artifactId>spring-boot-admin-starter-server</artifactId>
     <version>2.2.0-SNAPSHOT</version>
 </dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
Production needs to ensure the safety of monitoring -- >
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
 </dependency>

Then by adding@EnableAdminServerImport into configurationSpring Boot Admin ServerTo configure:

 @EnableAdminServer
 @SpringBootApplication
 public class SpringBootAdminApplication {
     public static void main(String[] args) {
         SpringApplication.run(SpringBootAdminApplication.class, args);
     }
 }

3.2 configure spring boot admin

Each application to be registered must includeSpring Boot Admin Client。 To protect endpoints, you should also add security dependenciesspring-boot-starter-security

 <dependency>
     <groupId>de.codecentric</groupId>
     <artifactId>spring-boot-admin-starter-client</artifactId>
     <version>2.2.0-SNAPSHOT</version>
 </dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
 </dependency>

And then in the client application’sapplication.ymlAdd the following configuration in:

spring:
     boot:
       admin:
         client:
     #Spring boot admin server address: http: // localhost: 8080, customizable 
             url:  http://localhost:8080 
     #By default, most endpoints are not exposed through HTTP, and we expose all endpoints. For production, you should carefully select the endpoints to expose.
  management:
    endpoints:
      web:
        exposure:
          include: '*'
    endpoint:
        health:
          show-details: ALWAYS

Start separatelySBAServer and client. Open the server pagehttp://localhost:8080The following monitoring interface will be entered:

Spring boot 2: use spring boot admin to monitor your application

And then we can getadmin-clientSpecific monitoring indicators:

Spring boot 2: use spring boot admin to monitor your application

If you have alreadySpring Cloud Discovery (eurekaconsulFor your application, noSpring Boot AdminClient. Just need toDiscoveryClientAdd toSpring Boot Admin Server, the rest is done through automatic configuration, which can be viewed through official examples.

4. Spring boot admin security access control

The application monitoring indicators are extremely sensitive data. Therefore, security access control must be increased in production to avoid leakage. You can use the security framework you are good at for access control. Here we useSpring SecurityTo protect usSpring Boot Admin

4.1 protect spring boot admin server

Add toSpring Security StarterDependence:

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

Set management account information

  spring:
    security:
      user:
        name: SBA_admin
        password: SBA_password
        roles: SBA_ADMIN

Configure secure path access control

 package cn.felord.admin.server.configuer;
 
 import de.codecentric.boot.admin.server.config.AdminServerProperties;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.http.HttpMethod;
 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.security.web.util.matcher.AntPathRequestMatcher;
 
 import java.util.UUID;
 
 /**
  * The type Security secure config.
  *
  * @author Felordcn
  * @since 2019 /10/19 23:33
  */
 @Configuration
 public class AdminServerSecurityConfig extends WebSecurityConfigurerAdapter {
     private final AdminServerProperties adminServer;
 
     /**
      * Instantiates a new Security secure config.
      *
      * @param adminServer the admin server
      */
     public AdminServerSecurityConfig(AdminServerProperties adminServer) {
         this.adminServer = adminServer;
     }
 
     @Override
     protected void configure(HttpSecurity http) throws Exception {
         // @formatter:off
         SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
         successHandler.setTargetUrlParameter("redirectTo");
         final String adminServerContextPath = this.adminServer.getContextPath();
         successHandler.setDefaultTargetUrl(adminServerContextPath+"/");
 
         http.authorizeRequests()
                 .antMatchers(adminServerContextPath + "/assets/**").permitAll() // <1>
                 .antMatchers(adminServerContextPath + "/login").permitAll()
                 .anyRequest().authenticated() // <2>
                 .and()
                 .formLogin().loginPage(adminServerContextPath + "/login").successHandler(successHandler).and() // <3>
                 .logout().logoutUrl(adminServerContextPath + "/logout").and()
                 .httpBasic().and() // <4>
                 .csrf()
                 .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // <5>
                 .ignoringRequestMatchers(
                         new AntPathRequestMatcher(adminServerContextPath + "/instances", HttpMethod.POST.toString()),  // <6>
                         new AntPathRequestMatcher(adminServerContextPath + "/instances/*", HttpMethod.DELETE.toString()),  // <6>
                         new AntPathRequestMatcher(adminServerContextPath + "/actuator/**")  // <7>
                 )
                 .and()
                 .rememberMe().key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600);
 
     }
 
 }

Then startSBA ServerThe serverhttp://localhost:8237You can enter the login page and enter the account key you have configured:

Spring boot 2: use spring boot admin to monitor your application

4.2 protect the spring boot admin client endpoint

After the server endpoint is under access control, the client needs permission to register. At the same time, some of the client’sActuatorEndpoints must also be protected.

Add toSpring Security StarterDependence:

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

Set security account information

  spring:
    security:
      user:
        name: SBA_admin
        password: SBA_password
        roles: SBA_ADMIN

Set server security account information

Will we be inSpring Boot AdminThe security account configured by the server is configured into the following properties:

boot:
     admin:
       client:
         #Spring boot admin server management account
         username: SBA_admin
         password: SBA_password

Protecting the actuator endpoint

When usedHTTP BasicWhen authenticating to protect the actuator endpoint,SBA ServerCredentials are required to access them. So we use the following configuration to authorize server accessActuatorEndpoints:

spring:
   boot:
     admin:
       client:
         instance:
           metadata:
 #Here is the account secret we set in the step of setting security account information in client   
             user.name: ${spring.security.user.name}
             user.password: ${spring.security.user.password}

Start the client application.

Please note: if you change the HTTP basic mode to access the endpoint, the above configuration will fail, and you may need to customizeHttpHeadersProviderTo meet your needs.

5. Advanced practice

Spring Boot AdminThere are also some features that we often use.

5.1 log view

By default, the log file is not accessible through the actuator endpoint, so theSpring Boot AdminNot visible in. To enable the log file actuator endpoint, you need to set thelogging.pathorlogging.file

Spring Boot AdminAll content that looks like a URL is detected and rendered as a hyperlink. Also supportANSIColor escape. You need to set a custom file log mode becauseSpring BootThe default mode for does not use color.

withlogging.fileFor example, we are at the clientapplication.ymlAdd the following configuration:

 logging:
    file: /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'

Then you canSBAConsole display:

Spring boot 2: use spring boot admin to monitor your application

5.2 add labels by application instance

TagsIt is an effective way for us to distinguish different instances of the same application. For example, we use it at the same timeSBAMonitoredspring.application.name=admin-clientThree examples of application are development(DEV), test(TEST). production(PROD) We can use (take development as an example):

Using information endpoints/info

info:
  tags:
    environment: DEV

Or configurationSBAMetadata:

 spring:
       boot:
         admin:
           client:
             instance:
               metadata:
                 tags:
                   environment: DEV 

Then we can view the specific information through the details interface:

Spring boot 2: use spring boot admin to monitor your application

5.3 email notification

Spring Boot AdminSupport the configuration of email to send email notifications so that we can handle system alerts in a timely manner.

Import mail dependency

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

Spring boot mail configuration

#Spring boot mail configuration 
 spring:
   mail: 
    host: smtp.qq.com
    username: [email protected]
    password: password
    properties:
      mail:
       smtp:
         auth: true
         starttls:
           enable: true
           required: true

Spring boot admin mail configuration

#SBA mail configuration
   boot:
    admin:
     notify:
       mail:
         from: [email protected] 
         to: [email protected]

In this way, you can receive email alerts. The nail robot notification function can also be used in China.

There are other functions that can be learned through official documents.

6. summary

Today we learned how to useSpring Boot AdminYesSpring BootApplication for monitoring. Also learned how toSpring Boot AdminFor security access control, there are also some useful advanced operations.
What needs to be explained here is that for some small applicationsSpring Boot AdminIt can be fully competent for monitoring function, and also very simple and easy to use.
But for large distributed cluster applications, I personally do not recommend usingSpring Boot Admin, need other more professionalAPMMonitoring, such as open sourceApache Skywalking 、Prometheus + GrafanaWait.

RelevantSBAFull code of actual combat can be concerned with official account number:FelordcnReplyadminObtain

Pay attention to the official account: Felordcn for more information

Personal blog: https://felord.cn

Spring boot 2: use spring boot admin to monitor your application

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]