Juejin. Im/Post /684490…

preface

Last year, we made the architectural transformation of microservices 1.0, but the service monitoring part didn’t catch up. Recently, I was given the task of monitoring all of our core microservices applications. Our micro-services applications are all SpringBoot applications, so we naturally thought of using SpringBoot’s Actuator module. (had not eaten pork total had heard pig call had seen pig run 🤪).

This is my summary of learning application of Spring Boot Actuator module after completing this work order. In this article, you can learn:

  • Quick Use of Spring Boot Actuator
  • Some important endpoints of Spring Boot Actuator
  • How to use the Actuator module to view thread dump information of current applications in real time
  • How to use the Actuator module to view heap information of current applications in real time
  • How do I change the log printing level of current applications in real time using the Actuator module
  • .

And then I’ll introduce:

  • TODO: SpringBoot microservice application integrates Prometheus + Grafana to monitor alarms

1. What is Spring Boot Actuator

The Spring Boot Actuator module provides production-level features such as health checks, auditing, metrics collection, and HTTP tracking to help us monitor and manage Spring Boot applications. This module is a collection of internal application information to expose to the external module, the above functions can be accessed through HTTP and JMX.

Because of its ability to expose internal information, the Actuator can also be integrated with external application monitoring systems (Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic, etc.). These monitoring systems provide excellent dashboards, graphics, analytics and alerts that help you monitor and manage your applications through a unified and friendly interface.

The Actuator uses Micrometer to integrate with these external application monitoring systems. As a result, external monitoring systems can be easily integrated with minimal configuration.

Micrometer provides a common API for performance data collection on the Java platform. Applications only need to use Micrometer’s common API to collect performance metrics. Micrometer will be responsible for the integration of different monitoring systems. This makes it easy to switch monitoring systems.

Compare Slf4j’s positioning in Java Logger.

2. Start quickly by creating a Spring Boot Actuator Demo

So let’s create a demo application.

  • You can create it with Spring Boot CLI:
Bdring-n = bDRing-demo bDRing-demoCopy the code
  • Or create via Spring Initializr:

  • Corresponding Maven dependencies:
<dependencies>
    ...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
    ...
</dependencies>
Copy the code
  • Corresponding Gradle dependencies:
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
}
Copy the code

Three, Endpoints

Spring Boot provides so-called endpoints for outsiders to access and interact with applications.

For example, the/Health endpoint provides some basic information about the health of the application. The Metrics endpoint provides some useful application metrics (JVM memory usage, system CPU usage, and so on).

These Actuator modules already have endpoints that we call native endpoints. According to the function of endpoints, we can be roughly divided into three categories:

  • Application configuration class: Obtains the configuration class information that is closely related to Spring Boot applications, such as application configuration, environment variables, and automatic configuration reports loaded in the application.
  • Metrics class: Gets metrics to monitor as the application runs, such as memory information, thread pool information, HTTP request statistics, and so on.
  • Operation control class: provides operation class functions such as shutting down applications.

For details on native endpoints, please refer to the official website.

Note that:

  • Each endpoint can be configured to be disabled or enabled individually
  • Instead of using the Actuator 1.x,Most endpoints in the Actuator 2.x are banned by default. – Default endpoints in Actuator 2.x have been added/actuatorPrefix. The default exposed two endpoints are/actuator/healthand/actuator/info

Endpoint exposure configuration

We can configure endpoints exposed through JMX and HTTP through the following configuration.

Property Default
management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include *
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include info, healt

You can open up all the surveillance points

management.endpoints.web.exposure.include=*
Copy the code

You can also select open sections, with “*” to expose all endpoints. If multiple endpoints are specified, separate them with “,”

management.endpoints.web.exposure.exclude=beans,trace
Copy the code

By default all monitoring point paths are in/Actuator /*, although this path can be customized if needed.

management.endpoints.web.base-path=/minitor
Copy the code

After the setup and restart, the next access address will be /minitor/*.

Now we follow the following configuration:

If multiple endpoints are specified, Separated by ", "management. Endpoints. Web. Exposure. Include = * # assignment rules ditto management endpoints. Web. Exposure. Exclude =Copy the code

Start the DEMO program, visit http://localhost:8080/actuator, check exposed endpoint:


This is shown because the JSON-handle plugin is installed in Chrome, which essentially returns a large chunk of JSON

Next, I’ll highlight a few of the more important endpoints.

5. Important endpoint resolution

5.1 /healthThe endpoint

The /health endpoint aggregates your application’s health metrics to check the health of your application. Application health information exposed by endpoints depends on:

management.endpoint.health.show-details=always
Copy the code

This property can be configured using one of the following values:

Name Description
never No details are displayed. The up or Down status is default
when-authorized The details will be displayed to the authenticated user. The authorized role can passmanagement.endpoint.health.rolesconfiguration
always Expose the details to all users

According to the above configuration, configuration as always, we start the project, visit http://localhost:8080/actuator/health port, you can see the message:

Does it feel like health information is a little sparse? Don’t worry, that’s because we created a basic Demo project that didn’t rely on many components.

The /health endpoint has many automatically configured health indicators: components such as Redis, RabbitMQ, DB, and so on. These health indicators are automatically assembled to collect information when your project has dependencies on corresponding components. The diskSpace node information above is the DiskSpaceHealthIndicator in action.

The above screenshots are taken from the official documentation

This is the/Health endpoint information for another of my projects.

If one component is abnormal, the overall status of the application service is Down. We can also configure to disable health monitoring for a component.

management.health.mongo.enabled: false
Copy the code

Or disable all automatically configured health indicators:

management.health.defaults.enabled: false
Copy the code

⭐ Custom Health Indicator

You can also customize a HealthIndicator by implementing the HealthIndicator interface or by inheriting the AbstractHealthIndicator class.

/** * @author Richard_yyf * @version 1.0 2020/1/16 */ @componentPublic Class CustomHealthIndicator extends AbstractHealthIndicator {@override protected void doHealthCheck(health. Builder Builder) throws Exception {// Use // If you throw an exception, status will be set to DOWN, The exception message is logged builder.up().withdetail ("app", "this project is healthy ").withdetail ("error", "Nothing, I'm very good"); }}Copy the code

End result:

5.2 /metricsThe endpoint

The /metrics endpoint is used to return various important metrics for the current application, such as memory information, thread information, garbage collection information, Tomcat, database connection pool, and so on.

{ "names": [ "tomcat.threads.busy", "jvm.threads.states", "jdbc.connections.active", "jvm.gc.memory.promoted", "http.server.requests", "hikaricp.connections.max", "hikaricp.connections.min", "jvm.memory.used", "jvm.gc.max.data.size", "jdbc.connections.max", .... ] }Copy the code

** differs from 1.x in that the interface does not show specific indicators, but only displays a list of indicators. ** To get detailed information about a metric, we can request specific metric information like this:

http://localhost:8080/actuator/metrics/{MetricName}
Copy the code

Such as I visit/physical/metrics/JVM memory. Max, return information is as follows:

You can also view individual sections using Query Param. For example you can access/physical/metrics/JVM memory. Max? Tag = id: Metaspace. The result:

5.3/loggersThe endpoint

The /loggers endpoint exposes information about all loggers configured internally for our program. We visit /actuator/loggers and you can see,

You can also access a single logger in the following way,

http://localhost:8080/actuator/loggers/{name}
Copy the code

For example, I now access to the root logger, http://localhost:8080/actuator/loggers/root

{    "configuredLevel": "INFO",    "effectiveLevel": "INFO"}
Copy the code

⭐ Changes the log level at run time

The feature I most want to mention is the ability to dynamically change your log level.

For example, we can change the log level of the root Logger in the following way. We only need to initiate a POST request URL for http://localhost:8080/actuator/loggers/root, POST a message is as follows:

{   "configuredLevel": "DEBUG"}
Copy the code

Think about how useful this feature is. If, in production, you want your application to output Debug messages so that you can diagnose exceptions, you can do this without restarting the application.

If you want to reset to the default value, change value to null

5.4 /infoThe endpoint

The /info endpoint can be used to display information about your application. I understand it to be the basic information of the program. And you can customize it to your needs in the application.properties configuration file (by default, this endpoint will only return an empty JSON content). :

Info. App. Name = physical - test - demoinfo. App. The encoding = utf-8 info. The app. Java source = 1.8 info. The app. Java. The target = 1.8 # in maven Apply to the maven project you can directly with the following properties of value # info. The app. The encoding = @ project. Build. SourceEncoding @ # [email protected]@# [email protected]@Copy the code

Start the project, visit http://localhost:8080/actuator/info:

{" app ": {" encoding" : "utf-8", "Java" : {" source ":" 1.8.0 comes with _131 ", "target" : "1.8.0 comes with _131"}, "name" : "actuator-test-demo" }}Copy the code

5.5 /beansThe endpoint

The/Beans endpoint returns the aliases, types, singletons, dependencies, and so on of all beans in the Spring container.

Visit http://localhost:8080/actuator/beans to return as follows:

5.6 /heapdumpThe endpoint

Visit: http://localhost:8080/actuator/heapdump will automatically generate a Jvm heap heapdumps file. You can open this file to view a memory snapshot using VisualVM, the Jvm monitoring tool that comes with the JDK.

5.7 /threaddumpThe endpoint

This endpoint is one that I personally find particularly useful for looking at threads during routine problem location. It mainly shows the thread name, thread ID, thread status, whether to wait for the lock resource, thread stack and other information. It just might not be intuitive to look at. Visit http://localhost:8080/actuator/threaddump to return to the following:

5.8 /shutdownThe endpoint

This endpoint belongs to the operation control class endpoint and can gracefully close the Spring Boot application. To use this feature you first need to enable it in the configuration file:

management.endpoint.shutdown.enabled=true
Copy the code

Due to shutdown interface by default only supports the POST request, we start the Demo program, to http://localhost:8080/actuator/shutdown launched a POST request. Return message:

{ "message": "Shutting down, bye..." }Copy the code

The application is then closed.

As the operation of opening and closing applications itself is very dangerous, we need to add some protection mechanisms when using them online, such as customizing the endpoint path of the Actuator and integrating Spring Security for Security verification. (Don’t open this endpoint unless it’s absolutely necessary.)

Integrate Spring Security to verify endpoint Security

Because the information about endpoints and the interactions they generate are very sensitive, unauthorized external access must be prevented. If you have Spring Security dependencies in your application, the default is to use form-based HTTP authentication to protect the endpoint.

If not, just add the corresponding dependency:

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

Once added, we need to define Security verification rules to override the default configuration of Spring Security.

Here I present two versions of the template configuration:

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.boot.actuate.context.ShutdownEndpoint; import org.springframework.boot.autoconfigure.security.servlet.PathRequest; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * @author Richard_yyf */ @Configuration public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter { /* * version1: * 1. Limit access to the '/shutdown' endpoint, allowing only ACTUATOR_ADMIN access to * 2. Allow external access to other endpoints * 3. Allow external access to static resources * 4. Allow external access '/' * 5. Other access needs to be verified * version2: * 1. Restrict access to all endpoints, allowing only ACTUATOR_ADMIN access to * 2. Allow external access to static resources * 3. Allow external access to '/' * 4. */ @override protected void configure(HttpSecurity HTTP) throws Exception {// version1 // HTTP // .authorizeRequests() // .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class)) // .hasRole("ACTUATOR_ADMIN") // .requestMatchers(EndpointRequest.toAnyEndpoint()) // .permitAll() // .requestMatchers(PathRequest.toStaticResources().atCommonLocations()) // .permitAll() // .antMatchers("/") // .permitAll() // .antMatchers("/**") // .authenticated() // .and() // .httpBasic(); // version2 http .authorizeRequests() .requestMatchers(EndpointRequest.toAnyEndpoint()) .hasRole("ACTUATOR_ADMIN") .requestMatchers(PathRequest.toStaticResources().atCommonLocations()) .permitAll() .antMatchers("/") .permitAll() .antMatchers("/**") .authenticated() .and() .httpBasic(); }}Copy the code

The configuration of application.properties is as follows:

# Spring Security Default user name and password
spring.security.user.name=actuator
spring.security.user.password=actuator
spring.security.user.roles=ACTUATOR_ADMIN
Copy the code

conclusion

That’s all for this article.

The corresponding source is available on Github. (github.com/Richard-yyf…).

If this article is helpful to you, please give me a thumbs up. This is my biggest motivation 🤝🤝🤗🤗.

Reference:

Docs. Spring. IO/spring – the boot…

www.ityouknow.com/springboot/…

Recent hot articles recommended:

1.1,000+ Java Interview Questions and Answers (2021)

2. Don’t use if/ else on full screen again, try strategy mode, it smells good!!

3. Oh, my gosh! What new syntax is xx ≠ null in Java?

4.Spring Boot 2.5 is a blockbuster release, and dark mode is exploding!

5. “Java Development Manual (Songshan version)” the latest release, quick download!

Feel good, don’t forget to click on + forward oh!