The characteristics of microservices determine that the deployment of functional modules is distributed. Most functional modules run on different machines and interact with each other through service calls. The business flows in the front and back office will be processed and passed by many microservices. How to quickly locate exceptions? Which link has a problem?
Under this framework, monitoring of microservices is particularly important. This article mainly combines Spring Boot Actuator to share with you the common usage of microservice Spring Boot Actuator, so that we can monitor and manage our microservices in daily life.
Actuator monitoring
Spring Boot uses the concept of "habits better than configuration" and uses package scanning and automated configuration mechanisms to load Spring beans that depend on jars. It does not require any Xml configuration to implement all Spring configurations. Although doing this makes our code very concise, the information such as instance creation and dependencies of the entire application are discrete to the annotations of various configuration classes, which makes it very difficult for us to analyze the various relationships between resources and instances in the entire application.
Actuator is an integrated function of introspection and monitoring of application systems provided by Spring Boot. You can view detailed information of application configuration, such as automated configuration information, created Spring beans, and some environmental properties.
Actuator monitoring can be done by adding the following dependencies
<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>
In order to ensure the security of the monitoring interface exposed by actuator, it is necessary to add security control dependencies spring-boot-start-security dependencies. When accessing application monitoring endpoints, verification information is required. Security dependencies, you can choose not to add or manage security, but it is not recommended.
Actuator's REST interface
Actuator monitoring is divided into two categories: native endpoints and user-defined endpoints; custom endpoints mainly refer to scalability. Users can define some more concerned indicators based on their actual applications and monitor them during the runtime.
Native endpoints provide numerous web interfaces in applications to understand the internal state of the application runtime. Native endpoints can be divided into three categories:
Actuator provides 13 interfaces, as shown in the following table.
| HTTP Methods | path | describe |
|---|---|---|
| GET | /autoconfig | An automatic configuration report is provided to record which automatic configuration conditions have been passed and which have not been passed. |
| GET | /configprops | Describe how to inject a bean with configuration properties (including default values) |
| GET | /beans | Describe all beans in the application context and their relationship |
| GET | /dump | Get a snapshot of thread activity |
| GET | /env | Get all environment attributes |
| GET | /env/{name} | Get specific environment attribute values based on name |
| GET | /health | Reports health metrics for the application, these values are provided by HealthIndicator's implementation class |
| GET | /info | Get custom information for the application, which is provided by the attributes headed by info |
| GET | /mappings | Describe all URI paths and their mapping relationship with the controller (including Actuator endpoints) |
| GET | /metrics | Report various application metrics, such as memory usage and HTTP request count |
| GET | /metrics/{name} | Reports the application metric value of the specified name |
| POST | /shutdown | Close the application and require endpoints.shutdown.enabled to be set to true |
| GET | /trace | Provide basic HTTP request tracking information (timestamp, HTTP header, etc.) |
Get started quickly
Related configurations
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: 8080management: security: enabled: false #Switch off security authentication port: 8088 #Admin port is adjusted to 8088 context-path: /monitor #actuator access path endpoints: shutdown: enabled: trueinfo: app: name: spring-boot-actuator version: 1.0.0
After the configuration is completed, the project can be started and you can continue to verify the various monitoring functions.
Detailed explanation of the command
autoconfig
Spring Boot's automatic configuration function is very convenient, but sometimes it also means that it is difficult to find out the specific cause when there is a problem. Use autoconfig to view the conditions under which a certain configuration takes effect during the application runtime, or why an automatic configuration does not take effect.
Start the sample project and visit: http://localhost:8088/monitor/autoconfig. The return part of the information is as follows:
{ "positiveMatches": { "DevToolsDataSourceAutoConfiguration": { "notMatched": [ { "condition": "DevToolsDataSourceAutoConfiguration.DevToolsDataSourceCondition", "message": "DevToolsDataSource 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 content of the properties set in the configuration file, as well as the default values of some configuration properties.
Start the sample project and visit: http://localhost:8088/monitor/configprops. The return part of the information is as follows:
{ ... "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
From the example, we can see that the bean's alias, type, whether a singleton, the address of the class, dependency and other information are displayed.
Start the sample project and visit: http://localhost:8088/monitor/beans. The return part of the information is as follows:
[ { "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 will generate a snapshot of the current thread activity. This function is very good, which makes it convenient for us to check the thread situation when we are locating problems in daily life. It mainly displays information such as thread name, thread ID, thread status, whether to wait for lock resources.
Start the sample project and visit: http://localhost:8088/monitor/dump. The return part of the information is as follows:
[ { "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 the system environment variables, including the environment variables used, JVM properties, command line parameters, jar packages used by the project, etc. Unlike configprops, configprops focuses on configuration information, while env focuses on operating environment information.
Start the sample project and visit: http://localhost:8088/monitor/env. The return part of the information is as follows:
{ "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 SpeTo avoid sensitive information being exposed to /env, all attributes named password, secret, key (or the last paragraph of the name is these) will be added to /env with "*". For example, if there is a property name database.password, then its display effect in /env is like this:
"database.password":"******"
Usage of /env/{name}
That is, 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
You can see that HealthEndPoint provides us with default monitoring results, including disk detection and database detection
Start the sample project and visit: http://localhost:8088/monitor/health Returns part of the information, the following JSON response is composed of state, disk space and db. Describes the overall health status of the application, UP indicates that the application is healthy. Disk space describes the total disk space, remaining disk space and minimum threshold. The application.properties threshold is configurable
{ "status": "UP", "diskSpace": { "status": "UP", "total": 209715195904, "free": 183253909504, "threshold": 10485760 } "db": { "status": "UP", "database": "MySQL", "hello": 1 }}In fact, looking at the Spring Boot-actuator source code, you will find that the information provided by HealthEndPoint is not limited to this. Under the org.springframework.boot.actuate.health package, you will find ElasticsearchHealthIndicator, RedisHealthIndicator, RabbitHealthIndicator, etc.
info
Info is the configuration information we configure in the configuration file starting with Info. For example, our configuration in the example project is:
info: app: name: spring-boot-actuator version: 1.0.0
Start the sample project and visit: http://localhost:8088/monitor/info The return part of the information is as follows:
{ "app": { "name": "spring-boot-actuator", "version": "1.0.0" }}mappings
Describe all URI paths and their mapping relationship with the controller
Start the sample project and visit: http://localhost:8088/monitor/mappings. The return part of the information is as follows:
{ "/**/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 is mainly monitoring JVM content usage, GC situation, class loading information, etc.
Start the sample project and visit: http://localhost:8088/monitor/metrics. The return part of the information is as follows:
{ "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.unloaded": 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 information provided by the /metrics interface is simply classified as follows:
| Classification | Prefix | Report content |
|---|---|---|
| Garbage collector | gc.* | The number of garbage collections that have occurred and the time spent on garbage collection are suitable for mark-cleaning garbage collectors and parallel garbage collectors (data originated from java.lang.management. GarbageCollectorMXBean) |
| Memory | mem.* | The amount of memory allocated to the application and the amount of free memory (data originated from java.lang. Runtime) |
| heap | heap.* | Current memory usage (data originated from java.lang.management.MemoryUsage) |
| Class loader | classes.* | The number of classes loaded and unloaded by the JVM class loader (data originated from java.lang. management.ClassLoadingMXBean) |
| system | processors, instance.uptime, uptime, systemload.average | System information, such as the number of processors (data originated from java.lang.Runtime), runtime (data originated from java.lang.management.RuntimeMXBean), load average (data originated from java.lang.management.OperatingSystemMXBean) |
| Thread pool | thread.* | The number of threads, daemon threads, and the peak number of threads after JVM startup (data originated from java.lang.management.ThreadMXBean) |
| Data Source | datasource.* | Number of data source connections (metadata from data source, only if the DataSource Bean exists in the Spring application context) |
| Tomcat session | httpsessions.* | Tomcat's active session number and maximum session number (the data comes from embedded Tomcat's beans, which are only available when running the application using embedded Tomcat server) |
| HTTP | counter.status., gauge.response. | Measures and counters for HTTP requests for various application services |
Explanation:
shutdown
Turn on the interface and elegantly close the Spring Boot application. To use this function, you must first enable it in the configuration file:
endpoints: shutdown: enabled: true
After the configuration is completed, start the sample project and visit: http://localhost:8088/monitor/shutdown Return part of the information is as follows:
{ "message": "Shutting down, bye..."}At this point you will find that the application has been closed.
trace
The /trace interface can report the detailed information of all web requests, including request methods, paths, timestamps, and request and response header information, and record the detailed information of each request.
Start the sample project, visit it first: http://localhost:8080/hello, and then execute it in the browser: http://localhost:8088/monitor/trace View the return 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 above information shows the details of /hello request.
Other configurations
Restrictions on access to sensitive information
According to the above table, if the authentication is false, it means that it is insensitive and can be accessed at will. Otherwise, it will be protected and cannot be accessed at will.
endpoints.mappings.sensitive=false
This requires setting up each one, which is more troublesome. The sensitive method requires the user to have the ACTUATOR role by default, so you can also set the security restrictions on the off:
management.security.enabled=false
Or cooperate with Spring Security for fine-grained control.
Enable and disable interfaces
Although Actuator's interfaces are useful, you don't necessarily 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, then disable all interfaces first, and then enable those few you want, 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 to everyone's learning and I hope everyone will support Wulin.com more.