- introduction
Under the current microservice architecture, many services will be deployed on different machines and interact with each other through service invocation. A complete business process will be processed and transmitted by many microservices. Therefore, 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 uses of Spring Boot Actuator to facilitate our daily use of monitoring and governance of our microservices.
Spring Boot Actuator helps us monitor the internal operation of the program, such as monitoring status, Bean loading, environment variables, log information, thread information, etc.
(understand the source code + VX: 445909108)
- Use of actor
2.1 project dependence
To use Spring Boot Actuator, you need to add the following dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
Note: since spring boot activator will expose the details of our service, in order to ensure security, it is recommended to add the related dependency spring boot starter security of security control. In this way, you need to enter authentication information when accessing the application monitoring endpoint. The required dependencies are as follows:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2.2 project configuration
Configuration file application YML as follows:
Code listing: 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 to access: http://localhost:8080/actuator , you can see that the page displays 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 default supported links. Only:
/actuator /actuator/health /health/{component}/{instance} /health/{component} /actuator/info
We can apply in the configuration file Add configuration in YML to enable 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 to enable all monitoring. Of course, you can also configure the monitoring to be enabled, such as management endpoints. web. exposure. include=beans,trace .
management. endpoint. health. Show details = always means health endpoint is enabled to display all details. By default, / Actor / health is public and does not display details.
management. endpoints. web. Base path = / monitor means to enable a separate url address to monitor the Spring Boot application. The default path is / Actor /. If this configuration is enabled, the access path will become / manage / *.
management.endpoint.shutdown.enabled=true enables the interface and closes Spring Boot.
In some business scenarios, our monitoring information may need to be obtained across domains. Spring Boot Actuator provides CORS related configurations to support cross domain calls. By default, CORS support is disabled only when management is set endpoints. web. cors. The allowed origins property cannot be enabled. The following configurations allow from https://www.geekdigging.com GET and POST calls for 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 rich monitoring interfaces through which we can understand the internal conditions of the application runtime. At the same time, actor supports users to customize and add endpoints. Users can define some indicators of concern according to their actual applications and monitor them during the run-time.
HTTP method path description
GET /auditevents displays audit event information for the current application
GET /beans displays a complete list of all Spring Beans in an application
GET /conditions displays the status of configuration classes and auto configuration classes and the reasons why they are applied or not applied
GET /configprops displays a collection list of all @ ConfigurationProperties
GET /env displays the properties of the ConfigurableEnvironment from Spring
GET /flyway displays the database migration path, if any
GET /health displays the health information of the application (a simple 'status' is displayed when accessing with an unauthenticated connection, and all information details are displayed when accessing with an authenticated connection)
GET /info displays any application information
GET /liquibase shows any Liquibase database migration path, if any
GET /metrics displays the currently applied metrics information
GET /mappings displays a collection list of all @ RequestMapping paths
GET /scheduledtasks displays scheduled tasks in the application
GET /sessions allows user sessions to be retrieved and deleted from the session store supported by Spring sessions. Not available when using Spring Session support for reactive Web applications.
POST /shutdown allows applications to shut down gracefully (not enabled by default)
GET /threaddump executes a thread dump
If you use a web application (Spring MVC, Spring WebFlux, or Jersey), you can also use the following interfaces:
HTTP method path description
GET /heapdump returns a GZip compressed hprof heap dump file
GET /jolokia exposes JMX beans over HTTP (WebFlux is not available when Jolokia is on the classpath)
GET /logfile returns the contents of the log file (if the logging.file or logging.path attribute is set). It supports using the HTTP Range header to receive some information of the contents of the log file
GET /prometheus displays metrics information in a format that can be captured by the Prometheus server
- Interface details
3.1 /health
health is mainly used to check the running status of applications, which is the most frequently used monitoring point. 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. Access: http://localhost:8080/actuator/health You can see the status of the application.
{ "status" : "UP" }
By default, the status of the final Spring Boot application is summarized by the HealthAggregator. The summary algorithm is:
Set status code order: setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN);.
Filter out unrecognized status codes.
If there is no status code, the status of the entire Spring Boot application is UNKNOWN.
Sort all collected status codes in the order of 1.
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. The Spring Boot Actuator automatically configures the following:
Name Description
Cassandra health indicator checks whether the Cassandra database is started.
The CouchbaseHealthIndicator checks whether the Couchbase cluster is started.
The DiskSpaceHealthIndicator checks for insufficient disk space.
The DataSourceHealthIndicator checks whether a connection to the DataSource can be established.
The ElasticsearchHealthIndicator checks whether the Elasticsearch cluster is started.
The influxdbhealth indicator checks whether the InfluxDB server is started.
The jmshealth indicator checks whether the JMS agent is started.
MailHealthIndicator checks whether the mail server is started.
The mongohealth indicator checks whether the Mongo database is started.
The neo4jhealth indicator checks whether the Neo4j server is started.
The Rabbit health indicator checks whether the Rabbit server is started.
RedisHealthIndicator checks whether the Redis server is started.
The solrhealth indicator checks whether the Solr server is started.
You can set management health. defaults. Use the enabled property to disable them all.
3.2 /info
Info is the information beginning with info configured in the configuration file, as we configured in the example project:
info: app: name: spring-boot-actuator version: 1.0.0
Start the project and open the browser to 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 and open the browser to access: http://localhost:8080/actuator/beans , some 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 and open the browser to access: http://localhost:8080/actuator/conditions , some 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 runtime checks the code under what conditions a configuration takes effect, or why an automatic configuration does not take effect.
3.5 /shutdown
This interface needs to be configured in the configuration file to enable this function:
management.endpoint.shutdown.enabled=true
After the configuration is completed, you can use curl to simulate the post request interface:
curl -X POST "http://localhost:8080/actuator/shutdown"
The display result is:
{ "message": "Shutting down, bye..." }
Note: spring boot starter security is added to the sample project. If you directly use post to access this interface, you will respond to 401, indicating that you have no permission to access. If you need to test this interface, please turn off spring boot starter security for the time being.
At this time, you can see that the example project we started has been closed.
3.6 /mappings
Describe all URI paths and their mapping to the controller
Start the project and open the browser to access: http://localhost:8080/actuator/mappings , some 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. It is convenient for us to view the thread when we locate the problem every day. It mainly displays the thread name, thread ID, thread status, whether to wait for lock resources and other information.
Start the project and open the browser to access: http://localhost:8080/actuator/threaddump , some 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 }]