Springboot uses Spring Boot Actuator to Monitor the application, springbootactuator

Source: Internet
Author: User
Tags spring boot actuator

Springboot uses Spring Boot Actuator to Monitor the application, springbootactuator

The characteristics of microservices determine that functional modules are deployed in a distributed manner. Most functional modules run on different machines and interact with each other through service calls, the frontend and backend business flows are processed and transmitted by many microservices. If an exception occurs, how can we quickly locate the problem?

In this framework, microservice monitoring is particularly important. This article mainly uses Spring Boot Actuator to share with you the common usage of Spring Boot Actuator for microservice monitoring and governance.

Actuator monitoring

Spring Boot uses the concept of "getting used to better configuration" and uses the packet scanning and automatic configuration mechanism to load Spring beans dependent on jar without any Xml configuration, all configurations of Spring can be implemented. Although this can make our code very concise, the information such as instance creation and dependency of the entire application is discrete to the annotations of various configuration classes, this makes it very difficult to analyze the relationships between Chinese sources and instances of the entire application.

Actuator is an integrated function provided by Spring Boot for introspection and monitoring of application systems. It allows you to view detailed information about application configurations, such as automated configuration information, created Spring beans, and some environment attributes.

The following dependencies can be added to Actuator monitoring:

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

To ensure the security of the monitoring interface exposed by actuator, you need to add the dependency on spring-boot-start-security for security control. verification information must be entered when accessing the application monitoring endpoint. Security dependency. You can choose not to add or manage Security, but it is not recommended to do so.

Actuator REST Interface

Actuator monitoring is divided into two types: Native endpoint and user-defined endpoint. Custom endpoint mainly refers to scalability. You can define some indicators of interest according to your actual application, perform monitoring during runtime.

The native endpoint provides many Web interfaces in the application to understand the internal status of the application running. The native endpoint can be divided into three types:

  1. Application configuration: You can view the static information of an application at runtime, such as automatic configuration information, loaded springbean information, yml file configuration information, environment information, and request ing information;
  2. Metric indicators: displays dynamic information during the runtime, such as stacks, request connections, health metrics, and metrics information;
  3. Operation Control: it refers to shutdown. You can send a request to disable the application monitoring function.

Actuator provides 13 interfaces, as shown in the following table.

HTTP Method Path Description
GET /Autoconfig An automatic configuration report is provided to record which automatic configuration conditions have passed and which fail
GET /Configprops Describes how to inject Bean into configuration attributes (including default values ).
GET /Beans Describes all the beans in the application context and their relationships.
GET /Dump Obtains a snapshot of a thread activity.
GET /Env Get all environment attributes
GET /Env/{name} Obtain specific environmental attribute values by name
GET /Health Reports the Health Metrics of an application. These values are provided by the HealthIndicator implementation class.
GET /Info Obtains application customization information, which is provided by the info header.
GET /Mappings Describes all URI paths and mappings between them and controllers (including Actuator endpoints ).
GET /Metrics Reports various application metrics, such as memory usage and HTTP request count
GET /Metrics/{name} Application metric value with the specified name of the report
POST /Shutdown Disable the application and set endpoints. shutdown. enabled to true.
GET /Trace Provides basic HTTP request tracking information (timestamp, HTTP header)

Quick Start

Related Configuration

Project dependency

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

Configuration File

Server: port: 8080 management: security: enabled: false # disable security authentication port: 8088 # change the management port to 8088 context-path:/monitor # actuator access path endpoints: shutdown: enabled: trueinfo: app: name: spring-boot-actuator version: 1.0.0
  1. Management. security. enabled = false by default, some information can be viewed only after security authentication is required. If you remove these security certifications, directly set management. security. enabled = false.
  2. Management. context-path =/monitor indicates that a separate url address is enabled to monitor the Spring Boot application. To ensure security, an independent port is generally enabled to access the monitoring information of the backend.
  3. Endpoints. shutdown. enabled = true enable the interface to disable Spring Boot

After the configuration is complete, start the project and continue to verify the various monitoring functions.

Command details

Autoconfig

The automatic configuration function of Spring Boot is very convenient, but sometimes it also means that it is difficult to find out the specific cause of the problem. You can use autoconfig to view the conditions under which a configuration takes effect or why an automatic configuration does not take effect when the application is running.

Start the example project and access http: // localhost: 8088/monitor/autoconfig to return the following information:

{ "positiveMatches": {  "DevToolsDataSourceAutoConfiguration": {   "notMatched": [    {     "condition": "DevToolsDataSourceAutoConfiguration.DevToolsDataSourceCondition",      "message": "DevTools DataSource Condition did not find a single DataSource bean"    }   ],    "matched": [ ]  },   "RemoteDevToolsAutoConfiguration": {   "notMatched": [    {     "condition": "OnPropertyCondition",      "message": "@ConditionalOnProperty (spring.devtools.remote.secret) did not find property 'secret'"    }   ],    "matched": [    {     "condition": "OnClassCondition",      "message": "@ConditionalOnClass found required classes 'javax.servlet.Filter', 'org.springframework.http.server.ServerHttpRequest'; @ConditionalOnMissingClass did not find unwanted class"    }   ]  } }}

Configprops

View the property content set in the configuration file and the default values of some configuration properties.

Start the example project and access http: // localhost: 8088/monitor/configprops to return the following information:

{ ... "environmentEndpoint": { "prefix": "endpoints.env", "properties": {  "id": "env",  "sensitive": true,  "enabled": true } }, "spring.http.multipart-org.springframework.boot.autoconfigure.web.MultipartProperties": { "prefix": "spring.http.multipart", "properties": {  "maxRequestSize": "10MB",  "fileSizeThreshold": "0",  "location": null,  "maxFileSize": "1MB",  "enabled": true,  "resolveLazily": false } }, "infoEndpoint": { "prefix": "endpoints.info", "properties": {  "id": "info",  "sensitive": false,  "enabled": true } } ...}

Beans

The following example shows the bean alias, type, Singleton, Class address, dependency, and other information.

Start the example project and access http: // localhost: 8088/monitor/beans to return the following information:

[ { "context": "application:8080:management", "parent": "application:8080", "beans": [  {  "bean": "embeddedServletContainerFactory",  "aliases": [     ],  "scope": "singleton",  "type": "org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory",  "resource": "null",  "dependencies": [     ]  },  {  "bean": "endpointWebMvcChildContextConfiguration",  "aliases": [     ],  "scope": "singleton",  "type": "org.springframework.boot.actuate.autoconfigure.EndpointWebMvcChildContextConfiguration$$EnhancerBySpringCGLIB$$a4a10f9d",  "resource": "null",  "dependencies": [     ]  } }]

Dump

The/dump interface generates a snapshot of the current thread activity. This function is very good, so that we can view the thread situation during routine troubleshooting. It mainly displays the thread name, thread ID, thread status, whether to wait for the lock resource, and other information.

Start the example project and access http: // localhost: 8088/monitor/dump to return the following information:

[ { "threadName": "http-nio-8088-exec-6", "threadId": 49, "blockedTime": -1, "blockedCount": 0, "waitedTime": -1, "waitedCount": 2, "lockName": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@1630a501", "lockOwnerId": -1, "lockOwnerName": null, "inNative": false, "suspended": false, "threadState": "WAITING", "stackTrace": [  {  "methodName": "park",  "fileName": "Unsafe.java",  "lineNumber": -2,  "className": "sun.misc.Unsafe",  "nativeMethod": true  },  {  "methodName": "park",  "fileName": "LockSupport.java",  "lineNumber": 175,  "className": "java.util.concurrent.locks.LockSupport",  "nativeMethod": false  },  {  "methodName": "await",  "fileName": "AbstractQueuedSynchronizer.java",  "lineNumber": 2039,  "className": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject",  "nativeMethod": false  },  ...  {  "methodName": "getTask",  "fileName": "ThreadPoolExecutor.java",  "lineNumber": 1067,  "className": "java.util.concurrent.ThreadPoolExecutor",  "nativeMethod": false  },  {  "methodName": "runWorker",  "fileName": "ThreadPoolExecutor.java",  "lineNumber": 1127,  "className": "java.util.concurrent.ThreadPoolExecutor",  "nativeMethod": false  },  {  "methodName": "run",  "fileName": "ThreadPoolExecutor.java",  "lineNumber": 617,  "className": "java.util.concurrent.ThreadPoolExecutor$Worker",  "nativeMethod": false  },  {  "methodName": "run",  "fileName": "TaskThread.java",  "lineNumber": 61,  "className": "org.apache.tomcat.util.threads.TaskThread$WrappingRunnable",  "nativeMethod": false  },  {  "methodName": "run",  "fileName": "Thread.java",  "lineNumber": 745,  "className": "java.lang.Thread",  "nativeMethod": false  } ], "lockedMonitors": [   ], "lockedSynchronizers": [   ], "lockInfo": {  "className": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject",  "identityHashCode": 372286721 } } ...]

Env

Displays the configuration information of system environment variables, including the environment variables used, JVM attributes, command line parameters, and jar packages used by the project. Unlike configprops, configprops focuses on configuration information, and env focuses on running environment information.

Start the example project and access http: // localhost: 8088/monitor/env to return the following information:

{ "profiles": [  ], "server.ports": { "local.management.port": 8088, "local.server.port": 8080 }, "servletContextInitParams": {  }, "systemProperties": { "com.sun.management.jmxremote.authenticate": "false", "java.runtime.name": "Java(TM) SE Runtime Environment", "spring.output.ansi.enabled": "always", "sun.boot.library.path": "C:\\Program Files\\Java\\jdk1.8.0_101\\jre\\bin", "java.vm.version": "25.101-b13", "java.vm.vendor": "Oracle Corporation", "java.vendor.url": "http://java.oracle.com/", "java.rmi.server.randomIDs": "true", "path.separator": ";", "java.vm.name": "Java HotSpot(TM) 64-Bit Server VM", "file.encoding.pkg": "sun.io", "user.country": "CN", "user.script": "", "sun.java.launcher": "SUN_STANDARD", "sun.os.patch.level": "", "PID": "5268", "com.sun.management.jmxremote.port": "60093", "java.vm.specification.name": "Java Virtual Machine Spe

To prevent sensitive information from being exposed to/env, "*" is added to/env for all attributes named password, secret, key (or the last segment in the name). For example, if the attribute name is database. password, the display effect in/env is as follows:

"Database. password ":"******"

/Env/{name} usage

The env extension can obtain the specified configuration information, such as http: // localhost: 8088/monitor/env/java. vm. version, return: {"java. vm. version ":" 25.101-b13 "}

Health

We can see that HealthEndPoint provides us with default monitoring results, including disk detection and database detection.

Start the example project and access http: // localhost: 8088/monitor/health to return some information. The following JSON response consists of status, disk space, and db. Describes the overall health status of an application. UP indicates that the application is healthy. Disk Space describes the total disk space, the remaining disk space, and the minimum threshold value. The application. properties threshold is configurable.

{ "status": "UP", "diskSpace": { "status": "UP", "total": 209715195904, "free": 183253909504, "threshold": 10485760 } "db": {  "status": "UP",  "database": "MySQL",  "hello": 1 }}

Check the source code of Spring Boot-actuator. You will find that the information provided by HealthEndPoint is not limited to this. In the org. springframework. boot. actuate. health Package, you will find ElasticsearchHealthIndicator, RedisHealthIndicator

Info

Info is the configuration information that we configured in the configuration file starting with Info. For example, the configuration in the example project is:

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

Start the example project and access http: // localhost: 8088/monitor/info. The returned information is as follows:

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

Mappings

Describes all URI paths and mappings between them and controllers.

Start the example project and access http: // localhost: 8088/monitor/mappings to return the following information:

{ "/**/favicon.ico": { "bean": "faviconHandlerMapping" }, "{[/hello]}": { "bean": "requestMappingHandlerMapping", "method": "public java.lang.String com.neo.controller.HelloController.index()" }, "{[/error]}": { "bean": "requestMappingHandlerMapping", "method": "public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)" }}

Metrics

One of the most important monitoring contents, mainly monitors JVM content usage, GC conditions, class loading information, and so on.

Start the example project and access http: // localhost: 8088/monitor/metrics to return the following information:

{ "mem": 337132, "mem.free": 183380, "processors": 4, "instance.uptime": 254552, "uptime": 259702, "systemload.average": -1.0, "heap.committed": 292864, "heap.init": 129024, "heap.used": 109483, "heap": 1827840, "nonheap.committed": 45248, "nonheap.init": 2496, "nonheap.used": 44269, "nonheap": 0, "threads.peak": 63, "threads.daemon": 43, "threads.totalStarted": 83, "threads": 46, "classes": 6357, "classes.loaded": 6357, "classes.unloaded": 0, "gc.ps_scavenge.count": 8, "gc.ps_scavenge.time": 99, "gc.ps_marksweep.count": 1, "gc.ps_marksweep.time": 43, "httpsessions.max": -1, "httpsessions.active": 0}

The following table lists the information provided by the/metrics interface:

Category Prefix Report Content
Garbage Collector Gc .* The number of spam collections that have occurred and the time consumed by the collection are applicable to the Mark-clear Garbage Collector and parallel garbage collector (data source from java. lang. management. GarbageCollectorMXBean)
Memory Mem .* The amount of memory allocated to the application and the amount of idle memory (data source from java. lang. Runtime)
Heap Heap .* Current memory usage (Data source: java. lang. management. MemoryUsage)
Class Loader Classes .* Number of classes loaded and detached by the JVM Class Loader (data source from java. lang. management. ClassLoadingMXBean)
System Processors, instance. uptime, uptime, systemload. average System information, such as the number of processors (data source from java. lang. runtime), Run Time (data source from java. lang. management. runtimeMXBean), average load (data source from java. lang. management. operatingSystemMXBean)
Thread Pool Thread .* Number of threads, daemon threads, and the peak number of threads after JVM startup (data source from java. lang. management. ThreadMXBean)
Data Source Datasource .* Number of data source connections (metadata from the data source. This information is available only when DataSource Bean exists in the Spring application context)
Tomcat session Httpsessions .* The number of active sessions and the maximum number of sessions of Tomcat (the data source is from the Bean of embedded Tomcat, which is available only when the embedded Tomcat server is used to run the Application)
HTTP Counter. status., gauge. response. Measure and counter of HTTP requests of various application services

Explanation:

  1. Note that some metric values here, such as data source and Tomcat session, only have data when running specific components in the application. You can also register your own metric information.
  2. HTTP counters and metric values must be described. The value after counter. status is the HTTP status code, followed by the requested path. For example, counter. status.200.metrics indicates the number of times the/metrics endpoint returns the 200 (OK) status code.
  3. The measurement information of HTTP is similar in structure, but another type of information is reported. They all start with gauge. response, indicating that this is the measurement information of the HTTP response. The prefix is followed by the corresponding path. The measured value is in milliseconds, reflecting the time consumed to process the path request recently.
  4. Note the following special values. The root path points to the root path or /. Star-star represents the paths that Spring considers as static resources, including images, JavaScript, and style sheets. It also contains the resources that cannot be found. This is why you often see counter. status.404.star-star, which is the number of requests that return the HTTP 404 (not found) status.
  5. The/metrics interface returns all available values, but you may only be interested in a specific value. To obtain a single value, you can add the corresponding key name after the URL. For example, to view the idle memory size, you can send a GET request to/metrics/mem. free. For example, for access: http: // localhost: 8088/monitor/metrics/mem. free, return: {"mem. free": 178123 }.

Shutdown

To enable this function, you must enable the following in the configuration file:

endpoints: shutdown: enabled: true

After the configuration is complete, start the sample project and access: http: // localhost: 8088/monitor/shutdown. Some information returned is as follows:

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

In this case, you will find that the application has been disabled.

Trace

The/trace interface can report the details of all Web requests, including the request method, path, timestamp, and header information of the request and response, and record the details of each request.

Start the sample project, access http: // localhost: 8080/hello, and then run http: // localhost: 8088/monitor/trace in the browser to view the returned information:

[ { "timestamp": 1516780334777, "info": {  "method": "GET",  "path": "/hello",  "headers": {  "request": {   "host": "localhost:8080",   "connection": "keep-alive",   "cache-control": "max-age=0",   "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",   "upgrade-insecure-requests": "1",   "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",   "accept-encoding": "gzip, deflate, br",   "accept-language": "zh-CN,zh;q=0.9",   "cookie": "UM_distinctid=16053ba344f1cd-0dc220c44cc94-b7a103e-13c680-16053ba3450751; Hm_lvt_0fb30c642c5f6453f17d881f529a1141=1513076406,1514961720,1515649377; CNZZDATA1260945749=232252692-1513233181-%7C1516085149; Hm_lvt_6d8e8bb59814010152d98507a18ad229=1515247964,1515296008,1515672972,1516086283"  },  "response": {   "X-Application-Context": "application:8080",   "Content-Type": "text/html;charset=UTF-8",   "Content-Length": "11",   "Date": "Wed, 24 Jan 2018 07:52:14 GMT",   "status": "200"  }  },  "timeTaken": "4" } }]

The preceding information shows the/hello request details.

Other configurations

Sensitive Information Access Restrictions

According to the table above, if the authentication is false, it indicates that the authentication is not sensitive and can be accessed at will. Otherwise, it is protected and cannot be accessed at will.

endpoints.mappings.sensitive=false

In this way, it is troublesome to set each item. By default, the user must have the ACTUATOR role. Therefore, you can disable the security restriction:

management.security.enabled=false

Or use Spring Security for fine-grained control.

Enable and disable Interfaces

Although Actuator interfaces are useful, you do not need all of them. By default, all interfaces (except/shutdown) are enabled. For example, to disable the/metrics interface, you can set it as follows:

endpoints.metrics.enabled = false

If you only want to open one or two interfaces, disable all interfaces first, and then enable those interfaces, which is more convenient.

endpoints.enabled = falseendpoints.metrics.enabled = true

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.