Detailed usage of Spring Boot Actuator monitoring

In enterprise applications, it is not enough to learn how to develop the SpringBoot application's capabilities and write unit tests, integrated tests, etc.It also needs to be monitored and managed in the actual software development.SpringBoot's Actuator module enables monitoring and management of applications.

Introduction to Actuator

In production systems, it is often necessary to monitor the operation and maintenance of the actual operation of the system (such as cpu, io, disk, db, business functions, etc.).In the SpringBoot project, the Actuator module provides a number of HTTP interface endpoints to provide internal state information when an application is running.

The Actuator module provides a module to monitor and manage the production environment, which can manage and monitor applications using http, jmx, ssh, telnet, and so on.It includes functions to monitor operations such as applied Auditing, health status information, metrics gathering statistics, and so on.Custom monitoring metrics that extend the Actuator Endpoint are also provided.These metrics are presented as JSON interface data.

Use of Actuator

Using Spring Boot Actuator requires the following dependencies to be added:

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

Actors are not integrated into automatic configurations by default but are presented as separate projects.When the above dependencies are introduced, two actuator-related items are introduced by default:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-actuator</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-actuator-autoconfigure</artifactId>
</dependency>

Where spring-boot-actuator is the function implementation and spring-boot-actuator-autoconfigure is the automatic configuration.

Note: Since SpringBoot Actuator exposes service details, it is recommended that you add a related dependency on spring-boot-starter-security for security control so that authentication information is required when accessing application monitoring endpoints.The following dependencies are required:

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

We will not expand on the use of security here, but you can configure the appropriate access password in the application file:

spring:
  security:
    user:
      name: admin
      password: admin

For convenience, we do not introduce security at this time.

After following the steps above, starting the SpringBoot project, the actuator automatically integrates the configuration by: http://localhost:8080/actuator Visit, the results are as follows:

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/actuator",
            "templated": false
        },
        "health": {
            "href": "http://localhost:8080/actuator/health",
            "templated": false
        },
        "health-component": {
            "href": "http://localhost:8080/actuator/health/{component}",
            "templated": true
        },
        "health-component-instance": {
            "href": "http://localhost:8080/actuator/health/{component}/{instance}",
            "templated": true
        },
        "info": {
            "href": "http://localhost:8080/actuator/info",
            "templated": false
        }
    }
}

Links supported by default are:

/actuator
/actuator/health
/health/{component}/{instance}
/health/{component}
/actuator/info

You can configure more monitoring information in the application configuration file:

management:
  endpoints:
    web:
      exposure:
        include: '*'
#      base-path: /monitor
  endpoint:
    health:
      show-details: always
    shutdown:
      enabled: true
  • Management.endpoints.web.exposure.include='*', which means that all monitoring is turned on or only those that need to be turned on can be configured, such as management.endpoints.web.exposure.include=beans,trace.
  • management.endpoint.health.show-details=always, health endpoint turns on to show all details.By default/actuator/health is public but does not show details.
  • management.endpoints.web.base-path=/monitor, enable the specified url address to access the root path, default path is/actuator/*, open access path becomes/monitor/*.
  • management.endpoint.shutdown.enabled=true, enable the interface to close SpringBoot.

Monitoring information, if required across calls, can be supported through CORS configuration and is disabled by default.Open after setting the management.endpoints.web.cors.allowed-origins property.

For example, allow from https://www.choupangxia.com Domain GET and POST calls:

management:
  endpoints:
    web:
      cors:
        allowed-origins: https://www.choupangxia.com
        allowed-methods: GET,POST

REST Interface

Spring Boot Actuator provides a very rich set of monitoring interfaces that allow you to understand the internal state of your application while it is running.Actuator also supports user-defined endpoints, which can be monitored at run time by defining some indicators of concern based on practical applications.

HTTP Method Route describe
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 and auto-configuration classes and the reasons why they were or were not applied.
GET /configprops Show a list of all @Configuration Properties collections
GET /env Displays properties of Configurable Environment from Spring.
GET /flyway Displays the database migration path, if any.
GET /health Display the health information of the application (a simple'status'is displayed when accessing with an unauthenticated connection, and full details are displayed when accessing with an authenticated connection)
GET /info Display any application information
GET /liquibase Show any Liquibase database migration paths, if any
GET /metrics Display metrics information for the current application
GET /mappings Displays a list of all @RequestMapping paths
GET /scheduledtasks Show scheduled tasks in the application
GET /sessions Allows retrieving and deletion of user sessions from session stores supported by Spring sessions.Support for reactive Web applications using Spring Session is not available.
POST /shutdown Allow applications to be closed in an elegant manner (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 Exposing JMX beans over HTTP (WebFlux is not available when Jolokia is on the class path)
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

Interface Details

health is primarily used to check the running status of an application, which is the most frequently used monitoring point.This interface is often used to show the running status of an application instance and the reasons why the application is not "healthy", such as database connections, insufficient disk space, and so on.

By default, health is open, accessing: http://localhost:8080/actuator/health You can see the status of the application.

{
    "status" : "UP"
}

Set the 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 SpringBoot application is UNKNOWN.Sort all collected status codes.Returns the first status code in an ordered sequence of status codes as the status of the entire SpringBoot application.

Healthcheck the Health of the app by combining several Health indices.The SpringBoot Actuator automatically configures the following:

Name describe
CassandraHealthIndicator Check that the Cassandra database is started.
CouchbaseHealthIndicator Check if the Couchbase cluster is started.
DiskSpaceHealthIndicator Check for insufficient disk space.
DataSourceHealthIndicator Check if a connection to DataSource can be established.
ElasticsearchHealthIndicator Check that the Elasticsearch cluster is started.
InfluxDbHealthIndicator Check that the InfluxDB server is started.
JmsHealthIndicator Check if the JMS proxy is started.
MailHealthIndicator Check that the mail server is started.
MongoHealthIndicator Check if the Mongo database is started.
Neo4jHealthIndicator Check that the Neo4j server is started.
RabbitHealthIndicator Check that the Rabbit server is started.
RedisHealthIndicator Check if the Redis server is started.
SolrHealthIndicator Check that the Solr server is started.

All can be disabled by setting the management.health.defaults.enabled property.

Native Endpoint

Native endpoints fall into three main categories:

  • Application Configuration Class: Get information about application configurations loaded in applications, environment variables, automated configuration reports, and other configuration classes that are closely related to Spring Boot applications.
  • Metrics class: Gets the metrics used to monitor an application while it is running, such as memory information, thread pool information, HTTP request statistics, and so on.
  • Operation Control Class: Provides operation class functions such as closing an application.

Apply Configuration Class

/conditions: This endpoint is used to obtain automation configuration reports for the application, including all candidates for automation configuration.The prerequisites for each candidate's automated configuration are also listed.This endpoint can help us easily find out why automation configurations are not working.

The report divides the automation configuration into two parts: one returned in positiveMatches is the automation configuration with successful condition matching and the other returned in negativeMatches is the automation configuration with unsuccessful condition matching.

Part of the code is as follows:

"contexts": {
        "application": {
            "positiveMatches": {
                "MsgAutoConfiguration": [
                    {
                        "condition": "OnClassCondition",
                        "message": "@ConditionalOnClass found required class 'com.secbro2.msg.MsgService'"
                    }
                ],
                "MsgAutoConfiguration#msgService": [
                    {
                        "condition": "OnPropertyCondition",
                        "message": "@ConditionalOnProperty (msg.enabled=true) matched"
                    },
                    {
                        "condition": "OnBeanCondition",
                        "message": "@ConditionalOnMissingBean (types: com.secbro2.msg.MsgService; SearchStrategy: all) did not find any beans"
                    }
                ],

/info: is the information configured in the configuration file that begins with info, such as configuring:

info:
  app:
    name: spring-boot-actuator
    version: 1.0.0

Return results:

{
  "app":{
    "name":"spring-boot-actuator",
    "version":"1.0.0"
  }
}

Parameters configured in info can also come from element nodes in the pom.xml file with attribute values enclosed by symbols *@*.The following:

info:
    build:
        artifact: @project.artifactId@
        name: @project.name@
        description: @project.description@
        ersion: @project.version@

Return results:

{
    "build": {
        "artifact": "spring-learn",
        "name": "spring-learn",
        "description": "Demo project for Spring Boot",
        "ersion": "0.0.1-SNAPSHOT"
    }
}

/beans: This endpoint is used to get all beans created in the application context.

{
	"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
		}
	}
}

The interface displays information such as the alias, type, singleton, address of the class, dependency, and so on for the bean.

/configprops: This endpoint is used to obtain a report of the attribute information configured in the application.

{
    "spring.transaction-org.springframework.boot.autoconfigure.transaction.TransactionProperties": {
        "prefix": "spring.transaction",
        "properties": {}
    }
}

The configuration information for the TransactionProperties property is shown above.

/mappings: This endpoint is used to return a controller mapping relationship report for all Spring MVCs.

{
  "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
      }]
    }
  }
}

/env: This endpoint is different from/configprops in that it is used to obtain all available environmental property reports for the application.These include environment variables, JVM properties, configuration configuration of the application, and parameters from the command line.

Metrics Class

The metrics provided by the application configuration class are static reports, while the report content provided by the endpoint of the measurement class is dynamic, providing some snapshot information of the application during operation, such as memory usage, HTTP request statistics, external resource metrics, and so on.These endpoints are very helpful for building monitoring systems in a microservice architecture.

/metrics: This endpoint is used to return important metrics for the current application, such as memory information, thread information, garbage collection information, and so on.

{
    "names": [
        "jvm.memory.max",
        "jvm.threads.states",
        "http.server.requests",
        "process.files.max",
        "jvm.gc.memory.promoted",
        "system.load.average.1m",
        "jvm.memory.used",
        "jvm.gc.max.data.size",
        "jvm.gc.pause",
        "jvm.memory.committed",
        "system.cpu.count",
        "logback.events",
        "tomcat.global.sent",
        "jvm.buffer.memory.used",
        "tomcat.sessions.created",
        "jvm.threads.daemon",
        "system.cpu.usage",
        "jvm.gc.memory.allocated",
        "tomcat.global.request.max",
        "tomcat.global.request",
        "tomcat.sessions.expired",
        "jvm.threads.live",
        "jvm.threads.peak",
        "tomcat.global.received",
        "process.uptime",
        "tomcat.sessions.rejected",
        "process.cpu.usage",
        "tomcat.threads.config.max",
        "jvm.classes.loaded",
        "jvm.classes.unloaded",
        "tomcat.global.error",
        "tomcat.sessions.active.current",
        "tomcat.sessions.alive.max",
        "jvm.gc.live.data.size",
        "tomcat.threads.current",
        "process.files.open",
        "jvm.buffer.count",
        "jvm.buffer.total.capacity",
        "tomcat.sessions.active.max",
        "tomcat.threads.busy",
        "process.start.time"
    ]
}

These are important measures from the example above:

  • System information: Includes number of processors, uptime and instance.uptime of runtime, system average load.
  • mem. *: Memory summary information, including the total amount of memory allocated to the application and the current amount of free memory.This information comes from java.lang.Runtime.
  • Heap. *: heap memory usage.This information comes from the java.lang.management.MemoryMXBean method obtained from the getHeapMemoryUsage method in the java.lang.management.MemoryUsage interface.
  • nonheap. *: Non-heap memory usage.This information comes from the java.lang.management.MemoryMXBean method obtained from the getNonHeapMemoryUsage method in the java.lang.management.MemoryUsage interface.
  • Threads. *: Thread usage, including number of threads, daemon, peak, and so on, all from java.lang.management.ThreadMXBean.
  • classes. *: Apply class statistics for loading and unloading.The data comes from java.lang.management.ClassLoadingMXBean.
  • Gc. *: Details of the garbage collector, including the number of garbage collections gc.ps_scavenge.count, the garbage collection elapsed time gc.ps_scavenge.time, the number of tag-sweep algorithms gc.ps_marksweep.count, and the tag-sweep algorithm elapsed time gc.ps_marksweep.time.The data comes from java.lang.management.GarbageCollector MXBean.
  • Httpsessions. *: Session usage of the Tomcat container.Includes the maximum number of sessions httpsessions.max and the number of active sessions httpsessions.active.This metric information is only available when an embedded Tomcat is introduced as an application container.
  • Gauge. *: One of the performance metrics for HTTP requests, which is used primarily to reflect an absolute value.For example, gauge.response.hello: 5 in the example above indicates that the last Hello request had a delay of 5 milliseconds.
  • Counter. *: One of the performance metrics for HTTP requests, which are used primarily as counters to record increases and decreases.As in the example above, counter.status.200.hello: 11 represents 11 times a hello request returns a 200 state.

/threaddump: A snapshot of the current thread activity is generated.It's easy for us to look at threads as we fix problems on a daily basis.It mainly shows information such as thread name, thread ID, state of thread, whether to wait for lock resource, etc.

{
	"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
	}]
}

/trace: This endpoint is used to return basic HTTP tracking information.By default, tracking information is stored in.

Operational Control Class

/shutdown: Configure in the configuration file to turn this on:

management.endpoint.shutdown.enabled=true

Simulate post requests to this interface using curl:

curl -X POST "http://localhost:8080/actuator/shutdown"

The results are as follows:

{
    "message": "Shutting down, bye..."
}

Summary

This article describes the basic functions and details of SpringBoot Actuator monitoring, and the next article will show you how it works in SpringBoot.Welcome to the public number "Procedural New Horizon".

Original Link: Detailed usage of Spring Boot Actuator monitoring>

<center><b>Program New Horizon</b>: Don't miss the excitement and growth</center>

Keywords: Spring jvm Tomcat Java

Added by oliverj777 on Wed, 20 Nov 2019 01:49:13 +0200