1. Introduction
In the current micro-service architecture, we will have many services deployed on different machines and interact with each other through service invocation. A complete business process will be processed and transmitted by many micro-services. So, how to know the health status of each service is particularly important.
Fortunately, Spring Boot provides us with the monitoring module Spring Boot Actuator. This article will discuss some common usages of Spring Boot Actuator to facilitate our monitoring and governance of our micro services in our daily use.
Spring Boot Actuator helps us to monitor the internal operation of the program, such as monitoring status, Bean loading, environment variables, log information, thread information and so on.
2. Use of Actuator
2.1 Engineering Dependence
Using Spring Boot Actuator requires adding the following dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
Note: Because Spring Boot Actuator will expose the details of our services, in order to ensure security, it is recommended to add the relevant dependency of security control spring-boot-starter-security, so that when accessing application monitoring endpoints, verification information needs to be input. The dependencies are as follows:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2.2 Engineering Configuration
The configuration file application.yml is as follows:
List of code: spring-boot-actuator/src/main/resources/application.yml
server: port: 8080 info: app: name: spring-boot-actuator version: 1.0.0 spring: security: user: name: admin password: admin
Now start the project and open the browser access: http://localhost 8080/actuator, you can see that the page shows the following json:
{ "_links":{ "self":{ "href":"http://localhost:8080/actuator", "templated":false }, "health":{ "href":"http://localhost:8080/actuator/health", "templated":false }, "health-component-instance":{ "href":"http://localhost:8080/actuator/health/{component}/{instance}", "templated":true }, "health-component":{ "href":"http://localhost:8080/actuator/health/{component}", "templated":true }, "info":{ "href":"http://localhost:8080/actuator/info", "templated":false } } }
These are the links supported by default, only:
/actuator /actuator/health /health/{component}/{instance} /health/{component} /actuator/info
We can add configuration in the configuration file application.yml to turn on more monitoring information:
management: endpoints: web: exposure: include: '*' # base-path: /monitor endpoint: health: show-details: always shutdown: enabled: true
- management.endpoints.web.exposure.include ='*'means that all monitoring is turned on. Of course, you can configure the monitoring that needs to be turned on, such as management.endpoints.web.exposure.include=beans,trace.
- management.endpoint.health.show-details=always means that health endpoint is open to display all details. By default, / actuator/health is public and does not show details.
- management.endpoints.web.base-path=/monitor represents enabling a separate url address to monitor Spring Book applications. The default path is / actuator /*. If this configuration is enabled, the access path becomes / manage ment /*.
- management.endpoint.shutdown.enabled=true enables the interface to close Spring Boot.
In some business scenarios, our monitoring information may need to be retrieved across boundaries. Spring Boot Actuator provides CORS-related configuration to support cross-domain calls. By default, CORS support is disabled and can only be enabled if the management.endpoints.web.cors.allowed-origins attribute is set. The following configuration allows GET and POST calls from the https://www.geekdigging.com domain:
management: endpoints: web: cors: allowed-origins: https://www.geekdigging.com allowed-methods: GET,POST
2.3 REST Interface
Spring Boot Actuator provides us with a very rich monitoring interface through which we can understand the internal state of the application running. At the same time, Actuator supports users to add endpoints customized. Users can define some indicators of concern according to their practical application, and monitor them at run time.
HTTP method | Route | describe |
---|---|---|
GET | /auditevents | Display audit event information for the current application |
GET | /beans | Display a complete list of all Spring Beans in an application |
GET | /conditions | Display the status of configuration and auto-configuration classes and the reasons why they are or are not applied |
GET | /configprops | Display a list of all @Configuration Properties collections |
GET | /env | Display the properties of Configurable Environment from Spring |
GET | /flyway | Display the database migration path, if any |
GET | /health | Display application health information (a simple'status'is displayed when accessing with an unauthenticated connection, and full information details are displayed when accessing with an authenticated connection) |
GET | /info | Display arbitrary application information |
GET | /liquibase | Show any Liquibase database migration path, if any |
GET | /metrics | Display metrics information for current applications |
GET | /mappings | Displays a list of collections of all @RequestMapping paths |
GET | /scheduledtasks | Display scheduled tasks in applications |
GET | /sessions | Allows retrieval and deletion of user sessions from session stores supported by Spring sessions. Spring Session support for reactive Web applications is not available. |
POST | /shutdown | Allow applications to be turned off gracefully (not enabled by default) |
GET | /threaddump | Execute a thread dump |
If you use a web application (Spring MVC, Spring WebFlux, or Jersey), you can also use the following interfaces:
HTTP method | Route | describe |
---|---|---|
GET | /heapdump | Returns a GZip-compressed hprof heap dump file |
GET | /jolokia | Exposure of JMX beans through HTTP (WebFlux is not available when Jolokia is on the classpath) |
GET | /logfile | Returns the contents of the log file (if logging.file or logging.path properties are set), supporting the use of HTTP Range headers to receive some information about the contents of the log file |
GET | /prometheus | Display metrics information in a format that can be captured by the Prometheus server |
3. Interface Details
3.1 /health
health is mainly used to check the running status of the application, which is one of the most frequently used monitoring points. Usually we use this interface 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's state is open. Start the project after adding dependencies. Access: http://localhost 8080/actuator/health can see the status of the application.
{ "status" : "UP" }
By default, the state of the final Spring Book application is aggregated by Health Aggregator, and the aggregation algorithm is:
- Set the status code order: setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN);.
- Filter out unrecognizable status codes.
- If there is no state code, the state of the Spring Book application is UNKNOWN.
- Sort all collected status codes in the order in 1.
- Returns the first state code in the sequence of ordered state codes as the state of the entire Spring Book application.
Health examines the health status of the application by combining several health indices. Spring Boot Actuator automatically configures the following:
Name | describe |
---|---|
CassandraHealthIndicator | Check whether the Cassandra database is started. |
CouchbaseHealthIndicator | Check whether the Couchbase cluster is started. |
DiskSpaceHealthIndicator | Check for insufficient disk space. |
DataSourceHealthIndicator | Check whether a connection DataSource can be established. |
ElasticsearchHealthIndicator | Check whether the Elastic search cluster has been started. |
InfluxDbHealthIndicator | Check that the InfluxDB server is started. |
JmsHealthIndicator | Check whether the JMS agent is started. |
MailHealthIndicator | Check that the mail server is started. |
MongoHealthIndicator | Check whether the Mongo database is started. |
Neo4jHealthIndicator | Check that the Neo4j server is started. |
RabbitHealthIndicator | Check whether the Rabbit server is started. |
RedisHealthIndicator | Check whether the Redis server is started. |
SolrHealthIndicator | Check that the Solr server is started. |
You can disable them all by setting the management.health.defaults.enabled attribute.
3.2 /info
Info is the information that we configure ourselves in the configuration file to begin with info, as we configure in the sample project:
info: app: name: spring-boot-actuator version: 1.0.0
Start the project and open the browser access: http://localhost:8080/actuator/info. The results are as follows:
{ "app":{ "name":"spring-boot-actuator", "version":"1.0.0" } }
3.3 /beans
Start the project, open the browser access: http://localhost:8080/actuator/beans, part of the results are 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": ["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": [] }, }, "parentId": null } } }
As you can see, this interface shows the alias, type, singleton, class address, dependency and other information of the bean.
3.4 /conditions
Start the project, open the browser access: http://localhost:8080/actuator/conditions, part of the results are as follows:
{ "contexts": { "application": { "positiveMatches": { "AuditAutoConfiguration#auditListener": [{ "condition": "OnBeanCondition", "message": "@ConditionalOnMissingBean (types: org.springframework.boot.actuate.audit.listener.AbstractAuditListener; SearchStrategy: all) did not find any beans" }], "AuditAutoConfiguration#authenticationAuditListener": [{ "condition": "OnClassCondition", "message": "@ConditionalOnClass found required class 'org.springframework.security.authentication.event.AbstractAuthenticationEvent'" }, { "condition": "OnBeanCondition", "message": "@ConditionalOnMissingBean (types: org.springframework.boot.actuate.security.AbstractAuthenticationAuditListener; SearchStrategy: all) did not find any beans" }], }, } } }
Using this interface, you can see that the application runs to see under what conditions a configuration takes effect, or what an automatic configuration does not take effect.
3.5 /shutdown
This interface first needs to be configured in the configuration file to turn on this function:
management.endpoint.shutdown.enabled=true
When the configuration is complete, you can use curl to simulate post requests for this interface:
curl -X POST "http://localhost:8080/actuator/shutdown"
The results are as follows:
{ "message": "Shutting down, bye..." }
Note: The example project adds spring-boot-starter-security. Direct post access to this interface will respond to 401, indicating no access. If you need to test this interface, please close spring-boot-starter-security temporarily.
Then you can see that the sample project we started has been closed.
3.6 /mappings
Describes all URI paths and their mapping to controllers
Start the project, open the browser access: http://localhost:8080/actuator/mappings, part of the results are as follows:
{ "handler": "Actuator web endpoint 'beans'", "predicate": "{GET /actuator/beans, produces [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/beans"], "produces": [{ "mediaType": "application/vnd.spring-boot.actuator.v2+json", "negated": false }, { "mediaType": "application/json", "negated": false }] } } }
3.7 /threaddump
/ The threaddump interface generates a snapshot of the current thread activity. This function is very good, so that we can check the thread situation when we locate the problem everyday. Mainly shows the thread name, thread ID, thread status, whether to wait for lock resources and other information.
Start the project, open the browser access: http://localhost:8080/actuator/threaddump, part of the results are as follows:
{ "threads": [{ "threadName": "Reference Handler", "threadId": 2, "blockedTime": -1, "blockedCount": 2, "waitedTime": -1, "waitedCount": 0, "lockName": null, "lockOwnerId": -1, "lockOwnerName": null, "daemon": true, "inNative": false, "suspended": false, "threadState": "RUNNABLE", "priority": 10, "stackTrace": [{ "classLoaderName": null, "moduleName": "java.base", "moduleVersion": "11.0.4", "methodName": "waitForReferencePendingList", "fileName": "Reference.java", "lineNumber": -2, "className": "java.lang.ref.Reference", "nativeMethod": true } ... "lockedMonitors": [], "lockedSynchronizers": [{ "className": "java.util.concurrent.locks.ReentrantLock$NonfairSync", "identityHashCode": 2060076420 }], "lockInfo": null ... { "threadName": "DestroyJavaVM", "threadId": 42, "blockedTime": -1, "blockedCount": 0, "waitedTime": -1, "waitedCount": 0, "lockName": null, "lockOwnerId": -1, "lockOwnerName": null, "daemon": false, "inNative": false, "suspended": false, "threadState": "RUNNABLE", "priority": 5, "stackTrace": [], "lockedMonitors": [], "lockedSynchronizers": [], "lockInfo": null }] }
4. Sample code
5. Reference:
Monitoring application using Spring Boot Actuator
Actuator of Spring Boot Official Documents
If my article is helpful to you, please pay close attention to the author's public number: Get the latest dry goods push:)