preface
What do you say? The more you learn, the more you don't know. Now you feel that learning is becoming more and more useless. If you don't learn, you can't. recently, you've been studying the contents related to SpringBoot. You're going to write some basic case codes first, make the follow-up research more thorough, write some meaningful analysis articles and publish them. Let's start now!
Introduction to Actuator
Definition of Actuator An actor is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change Translation: Definition of actuator Actuator is a manufacturing term that refers to a mechanical device used to move or control something. The actuator can produce a large amount of motion from a small change.
In the production environment, it is often necessary to monitor the actual operation of the system (such as cpu, io, disk, db, business function and other indicators). In the SpringBoot project, the Actuator module provides many HTTP interface endpoints to provide the internal state information of the application runtime.
The Actuator module provides a module for monitoring and managing the production environment. You can use http, jmx, ssh, telnet, etc. to manage and monitor applications. Including application Auditing, health status information, statistics of metrics gathering and other monitoring and operation and maintenance functions. At the same time, it provides user-defined monitoring indicators that can extend the actor Endpoint. These indicators are presented in the form of JSON interface data.
It should be noted that the activator monitoring settings of SpringBoot 1.x and 2.X are very different. Not only do they provide different endpoint paths, but also the configuration of application.properties. The description here is springboot version 2.5.3. For version 2.X, see the official website description. It also provides cross domain support and server monitoring, such as Redis and influxdb, You can view the official website information
Using Spring Boot Actuator
If you want to use the monitoring function provided by Spring Boot Actuator, you need to add relevant maven dependency dependencies first
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <!-- actuator rely on --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- WEB rely on --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
As long as this maven dependency is added, SpringBoot will automatically open / Actor / health and / Actor / Info endpoints at runtime, and then you can view the operation of the current SpringBoot application through these two endpoints, such as automation configuration information, created Spring beans and some environment properties.
In order to ensure the security of the monitoring interface exposed by the actor, the spring boot start security dependency of security control needs to be added. When accessing the application monitoring endpoint, the authentication information needs to be entered.
<dependency> <!--Security rely on --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Security dependency. I choose not to add it here. Shiro uses it more in its own projects and is not very familiar with security. Security management is not carried out here. If security management is added, you only need to configure the user name and password in the configuration file, as shown below
spring: security: user: name: admin password: 123456
Actuator actually provides more diversified endpoints. Let's monitor SpringBoot Application. However, due to security factors, these endpoints need to be configured in the configuration file. The detailed configuration scheme is described below.
All endpoint s provided by actor
I use springboot version 2.5.3, Spring Boot official documentation
The key feature of Spring Boot Actuator is to provide many Web interfaces in the application to understand the internal situation of the application runtime. Actuator provides 13 interfaces, which can be divided into three categories: configuration interface, measurement interface and other interfaces, as shown in the table below.
HTTP method | route | describe |
---|---|---|
GET | /auditevents | Display the audit events exposed by the application (such as authentication entry and order failure) |
GET | /beans | Describe all beans in the application context and their relationships |
GET | /conditions | It is / autoconfig of 1.0, which provides an effective condition of automatic configuration, and records which automatic configuration conditions pass and which fail |
GET | /configprops | Describes how configuration properties (including default values) are injected into beans |
GET | /env | Get all environment properties |
GET | /env/{name} | Gets a specific environment attribute value by name |
GET | /flyway | Provide a copy of Flyway database migration information |
GET | /liquidbase | Displays detailed information about Liquibase database migration |
GET | /health | Reports the health indicators of the application, which are provided by the implementation class of the HealthIndicator |
GET | /heapdump | dump an application's JVM heap information |
GET | /httptrace | Display HTTP footprints, the last 100 HTTP requests / repsponses |
GET | /info | Get the customization information of the application, which is provided by the attribute beginning with info |
GET | /logfile | Returns the contents of log file (if logging.file or logging.path is set) |
GET | /loggers | Display and modify configured loggers |
GET | /metrics | Reports various application metrics such as memory usage and HTTP request count |
GET | /metrics/{name} | Reports application metrics with a specified name |
GET | /scheduledtasks | Display the scheduled task information in the application |
GET | /sessions | If we use Spring Session to display the HTTP sessions information in the application |
POST | /shutdown | Close the application and require endpoints.shutdown.enabled to be set to true |
GET | /mappings | Describe all URI paths and their mapping to the controller (including the actor endpoint) |
GET | /threaddump | Get a snapshot of thread activity |
Detailed description of configuration file
- Modify profile
management: endpoints: web: exposure: # This means that all endpoints are enabled (excluding shutdown) include: '*' # It should be noted that the * sign here must be added with single quotation marks, otherwise an error will be reported # The following method is to open the specified endpoints interface # include: beans,mappings,loggers # Exclude can be used to close some specified interfaces. Exclude is usually used together with include. First, use include to open all interfaces, and then exclude an interface exclude: beans # Configure the path of custom / actor. If it is written in this way, the original default path of / Actor / XXX will become / mobaijun/xxx, which can be used to prevent others from guessing base-path: mobaijun # Version 2.X provides cross domain support. Using Spring MVC or Spring WebFlux, you can configure the Web endpoint of Actuator to support such scenarios. cors: # If you don't know about cross domain, you can visit my article published some time ago: https://www.mobaijun.com/posts/2298002216.html allowed-origins: * allowed-methods: * # If you want to start / Actor / shutdown, add the following additional configuration endpoint: shutdown: enabled: true
Start the Spring Boot application. If it is developed in IDEA, you can open the Terminal and open a Terminal for testing. There is a defect in this test, that is, the JSON data cannot be formatted and stacked together. You can also test in the browser. You can intuitively view the JSON data by loading a JSON Viewer under the chrome browser.
# Please add curl parameter in front of the console as follows $ curl http://localhost:8080/actuator
- The browser does not need to add a request instruction. The request contents are as follows: http://localhost:8080/actuator
{ "_links": { "self": { "href": "http://localhost:8080/actuator", "templated": false }, "beans": { "href": "http://localhost:8080/actuator/beans", "templated": false }, "caches-cache": { "href": "http://localhost:8080/actuator/caches/{cache}", "templated": true }, "caches": { "href": "http://localhost:8080/actuator/caches", "templated": false }, "health": { "href": "http://localhost:8080/actuator/health", "templated": false }, "health-path": { "href": "http://localhost:8080/actuator/health/{*path}", "templated": true }, "info": { "href": "http://localhost:8080/actuator/info", "templated": false }, "conditions": { "href": "http://localhost:8080/actuator/conditions", "templated": false }, "shutdown": { "href": "http://localhost:8080/actuator/shutdown", "templated": false }, "configprops": { "href": "http://localhost:8080/actuator/configprops", "templated": false }, "configprops-prefix": { "href": "http://localhost:8080/actuator/configprops/{prefix}", "templated": true }, "env": { "href": "http://localhost:8080/actuator/env", "templated": false }, "env-toMatch": { "href": "http://localhost:8080/actuator/env/{toMatch}", "templated": true }, "loggers": { "href": "http://localhost:8080/actuator/loggers", "templated": false }, "loggers-name": { "href": "http://localhost:8080/actuator/loggers/{name}", "templated": true }, "heapdump": { "href": "http://localhost:8080/actuator/heapdump", "templated": false }, "threaddump": { "href": "http://localhost:8080/actuator/threaddump", "templated": false }, "metrics": { "href": "http://localhost:8080/actuator/metrics", "templated": false }, "metrics-requiredMetricName": { "href": "http://localhost:8080/actuator/metrics/{requiredMetricName}", "templated": true }, "scheduledtasks": { "href": "http://localhost:8080/actuator/scheduledtasks", "templated": false }, "mappings": { "href": "http://localhost:8080/actuator/mappings", "templated": false } } }
Detailed explanation of common interfaces
health
health is mainly used to check the running status of applications, which is a monitoring point with the highest frequency. This interface is usually used to remind us of the running status of the application instance and the reasons why the application is not "healthy", such as database connection, insufficient disk space, etc.
By default, health is open. Start the project after adding dependencies,
# View the status of the application $ curl http://localhost:8080/actuator/health {"status":"UP"}
By default, the status of the final Spring Boot application is summarized by the HealthAggregator. The summary algorithm is:
- 1. Set status code sequence: setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN);.
- 2 filter out unrecognized status codes.
- 3 if there is no status code, the status of the whole Spring Boot application is UNKNOWN.
- 4 sort all collected status codes in the order of 1.
- 5 returns the first status code in the ordered status code sequence as the status of the entire Spring Boot application.
Health checks the health of the application by combining several health indexes. Spring Boot Actuator has several predefined health indicators, such as DataSourceHealthIndicator, DiskSpaceHealthIndicator, MongoHealthIndicator, RedisHealthIndicator, etc. it uses these health indicators as part of the health check.
For example, if your application uses Redis, the redishealth indicator will be regarded as part of the check; if you use MongoDB, the mongohealth indicator will be regarded as part of the check.
You can turn off specific health check indicators in the configuration file, such as turning off the health check of redis:
management.health.redise.enabled=false
By default, all these health indicators are considered as part of the health examination.
info
Info is the configuration information that starts with info in our configuration file. For example, our configuration in the example project is:
info: app: name: spring-boot-actuator version: 1.0.0
visit: http://localhost:8080/actuator/info Some information returned is as follows:
$ curl http://localhost:8080/actuator/info {"app":{"name":"spring-boot-actuator","version":"1.0.0"}}
beans
As can be seen from the example, the alias, type, singleton, class address, dependency and other information of the bean are displayed.
visit: http://localhost:8080/actuator/beans Some information returned is as follows:
"contexts": { "application": { "beans": { "endpointCachingOperationInvokerAdvisor": { "aliases": [ ], "scope": "singleton", "type": "org.springframework.boot.actuate.endpoint.invoker.cache.CachingOperationInvokerAdvisor", "resource": "class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.class]", "dependencies": [ "org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration", "environment" ] }, "defaultServletHandlerMapping": { "aliases": [ ], "scope": "singleton", "type": "org.springframework.web.servlet.HandlerMapping", "resource": "class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]", "dependencies": [ "org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration" ] } ..............................................................................
conditions
The automatic configuration function of Spring Boot is very convenient, but sometimes it means that it is difficult to find the specific reason for the problem. Conditions can be used to check the code when the application runs. Under what conditions does a configuration take effect, or why an automatic configuration does not take effect.
visit: http://localhost:8080/actuator/conditions Some information returned is as follows:
"contexts": { "application": { "positiveMatches": { "AuditEventsEndpointAutoConfiguration": [ { "condition": "OnAvailableEndpointCondition", "message": "@ConditionalOnAvailableEndpoint no property management.endpoint.auditevents.enabled found so using endpoint default; @ConditionalOnAvailableEndpoint marked as exposed by a 'management.endpoints.jmx.exposure' property" } ], "BeansEndpointAutoConfiguration": [ { "condition": "OnAvailableEndpointCondition", "message": "@ConditionalOnAvailableEndpoint no property management.endpoint.beans.enabled found so using endpoint default; @ConditionalOnAvailableEndpoint marked as exposed by a 'management.endpoints.jmx.exposure' property" } ] ..............................................................................
heapdump
Returns a GZip compressed JVM heap dump
visit: http://localhost:8080/actuator/heapdump A Jvm heap file heapdump will be automatically generated. We can use the Jvm monitoring tool VisualVM provided with JDK to open this file and view the memory snapshot. Click load snapshot and select the automatically generated heapdump, as shown in the following figure:
shutdown
Open the interface and close the Spring Boot application gracefully. To use this function, you first need to open it in the configuration file:
management.endpoint.shutdown.enabled=true
After the configuration is completed, start the sample project and use curl to simulate a post request to access the shutdown interface.
The shutdown interface only supports post requests by default.
$ curl -X POST "http://localhost:8080/actuator/shutdown" {"message":"Shutting down, bye..."}
At this point, you will find that the application has been closed.
mappings
Describe all URI paths and their mapping to the controller
visit: http://localhost:8080/actuator/mappings Some information returned is as follows:
contexts": { "application": { "mappings": { "dispatcherServlets": { "dispatcherServlet": [ { "handler": "Actuator web endpoint 'health'", "predicate": "{GET [/actuator/health], produces [application/vnd.spring-boot.actuator.v3+json || application/vnd.spring-boot.actuator.v2+json || application/json]}", "details": { "handlerMethod": { "className": "org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping.OperationHandler", "name": "handle", "descriptor": "(Ljavax/servlet/http/HttpServletRequest;Ljava/util/Map;)Ljava/lang/Object;" }, "requestMappingConditions": { "consumes": [ ], "headers": [ ], "methods": [ "GET" ], "params": [ ], "patterns": [ "/actuator/health" ] ..............................................................................
threaddump
The threaddump interface will generate a snapshot of the current thread activity. This function is very good. It is convenient for us to view the thread when we locate the problem. It mainly displays the thread name, thread ID, thread status, whether to wait for lock resources, etc.
visit: http://localhost:8080/actuator/threaddump Some information returned is as follows:
threads": [ { "threadName": "DestroyJavaVM", "threadId": 38, "blockedTime": -1, "blockedCount": 0, "waitedTime": -1, "waitedCount": 0, "lockName": null, "lockOwnerId": -1, "lockOwnerName": null, "inNative": false, "suspended": false, "threadState": "RUNNABLE", "stackTrace": [ ], "lockedMonitors": [ ], "lockedSynchronizers": [ ], "lockInfo": null } ..............................................................................
In case of production problems, you can detect the tasks being executed by the application through the thread snapshot of the application.
Reference article:
Spring Boot Actuator: Production-ready Features