Introduction to Spring Boot Actuator

Posted by warriors2003 on Fri, 24 Dec 2021 14:32:32 +0100

Recently, I was watching the Spring Cloud micro service practical war. Since the introduction to the activator monitoring endpoint has been outdated in the past few years, this article is updated.

Spring Boot version: 2.5 three

First meet actor

It is very simple to introduce this module into the existing Spring Boot application, just in POM In the dependencies node of XML, add the dependency of Spring Boot starter actuator as follows:

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

Restart the application after adding the dependency. At this point, we can see the output shown in the following figure in the console:

The above figure shows that an endpoint is exposed in the path / actor. The endpoint is not created in the program itself, but a monitoring and management endpoint automatically created by the spring boot starter actor module according to the application dependency and configuration. Through these endpoints, we can obtain various monitoring indicators of the application in real time. For example, by accessing the / Actor / health endpoint, we can obtain the following returned application health information:

{
	status: "UP"
}

Where are the many endpoints listed in the original text? After searching, it is because it is not exposed for security in the web scenario, so we need to Set in the properties file:

management.endpoints.web.exposure.include=*

When you start the application again, you can have the following outputs:

Through access http://localhost:8080/actuator , you may see all endpoints:

{
	_links: {
		self: {
			href: "http://localhost:8080/actuator",
			templated: false
		},
		beans: {
			href: "http://localhost:8080/actuator/beans",
			templated: false
		},
		caches-cache: {
			href: "http://localhost:8080/actuator/caches/{cache}",
			templated: true
		},
		caches: {
			href: "http://localhost:8080/actuator/caches",
			templated: false
		},
		health: {
			href: "http://localhost:8080/actuator/health",
			templated: false
		},
		health-path: {
			href: "http://localhost:8080/actuator/health/{*path}",
			templated: true
		},
		info: {
			href: "http://localhost:8080/actuator/info",
			templated: false
		},
		conditions: {
			href: "http://localhost:8080/actuator/conditions",
			templated: false
		},
		configprops: {
			href: "http://localhost:8080/actuator/configprops",
			templated: false
		},
		configprops-prefix: {
			href: "http://localhost:8080/actuator/configprops/{prefix}",
			templated: true
		},
		env: {
			href: "http://localhost:8080/actuator/env",
			templated: false
		},
		env-toMatch: {
			href: "http://localhost:8080/actuator/env/{toMatch}",
			templated: true
		},
		loggers-name: {
			href: "http://localhost:8080/actuator/loggers/{name}",
			templated: true
		},
		loggers: {
			href: "http://localhost:8080/actuator/loggers",
			templated: false
		},
		heapdump: {
			href: "http://localhost:8080/actuator/heapdump",
			templated: false
		},
		threaddump: {
			href: "http://localhost:8080/actuator/threaddump",
			templated: false
		},
		metrics-requiredMetricName: {
			href: "http://localhost:8080/actuator/metrics/{requiredMetricName}",
			templated: true
		},
		metrics: {
			href: "http://localhost:8080/actuator/metrics",
			templated: false
		},
		scheduledtasks: {
			href: "http://localhost:8080/actuator/scheduledtasks",
			templated: false
		},
		mappings: {
			href: "http://localhost:8080/actuator/mappings",
			templated: false
		}
	}
}

Click the specific link to get a more detailed description.

Native endpoint

By adding the spring boot starter actuator module in the previous section, we have a preliminary understanding of it. Next, let's introduce in detail some of the native endpoints already implemented in the spring boot starter actor module. According to the role of endpoints, we can divide native endpoints into three categories:

  • Application configuration class: obtain the application configuration, environment variables, automatic configuration reports and other configuration class information closely related to Spring Boot applications loaded in the application.
  • Metrics class: get metrics used for monitoring during application running, such as memory information, thread pool information, HTTP request statistics, etc.
  • Operation control class: provides operation class functions such as closing applications.
    Let's learn in detail what useful information and powerful functions these three types of endpoints can provide us, and how to extend and configure them.

Application configuration class

In order to improve the complicated configuration content of traditional Spring applications, Spring Boot adopts the mechanism of package scanning and automatic configuration to load the contents originally concentrated in xml files. Although this approach makes our code very concise, the instance creation and dependency of the whole application are dispersed to the annotation of each configuration class, which makes it very difficult for us to analyze the various relationships between resources and instances in the whole application. Such endpoints can help us easily obtain a series of detailed reports on Spring application configuration, such as reports on automatic configuration, reports on Bean creation, reports on environment properties, etc.

  • /conditions (original / autoconfig): this endpoint is used to obtain the automation configuration report of the application, including all candidates for automation configuration. It also lists whether each prerequisite for automation configuration of each candidate is met. Therefore, this endpoint can help us find out the specific reasons why some automation configurations are not effective. The content of this report will be automated The configuration content is divided into two parts:
    • The automatic configuration with successful condition matching is returned in positiveMatches
    • The automatic configuration with unsuccessful condition matching is returned in negativeMatches
    • Unconditional class no conditional automation configuration is set
{
	contexts: {
		application: {
			positiveMatches: {
				AuditEventsEndpointAutoConfiguration: [
					{
						condition: "OnAvailableEndpointCondition",
						message: "@ConditionalOnAvailableEndpoint no property management.endpoint.auditevents.enabled found so using endpoint default; @ConditionalOnAvailableEndpoint marked as exposed by a 'management.endpoints.web.exposure' property"
					},
					...
				],
				...
			},
			negativeMatches: {
				RabbitHealthContributorAutoConfiguration: {
					notMatched: [
						{
							condition: "OnClassCondition",
							message: "@ConditionalOnClass did not find required class 'org.springframework.amqp.rabbit.core.RabbitTemplate'"
						}
					],
					...
			},
			unconditionalClasses: [
				"org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration",
				"org.springframework.boot.actuate.autoconfigure.availability.AvailabilityHealthContributorAutoConfiguration",
				"org.springframework.boot.actuate.autoconfigure.info.InfoContributorAutoConfiguration",
				"org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration",
				"org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration",
				"org.springframework.boot.actuate.autoconfigure.health.HealthContributorAutoConfiguration",
				"org.springframework.boot.actuate.autoconfigure.metrics.integration.IntegrationMetricsAutoConfiguration",
				"org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration",
				"org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration",
				"org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration",
				"org.springframework.boot.actuate.autoconfigure.web.server.ManagementContextAutoConfiguration"
			]
	],

From the above example, we can see that each automation configuration candidate has a series of conditions. For example, there is no successfully matched rabbithealthcontributor autoconfiguration configuration above. Its prerequisite is to include org. Org in the project springframework. amqp. rabbit. core. Rabbittemplate class, since we have not introduced relevant dependencies, it will not execute automatic configuration content. Therefore, when we find that some desired configurations are not effective, we can view the specific reasons for the failure through this endpoint.

  • /Bean s: this endpoint is used to obtain 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: [
						"org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration",
						"environment"
					]
				},
				...
			},
			parentId: null
		}
	}
}

In the above example, we can see that each bean appears as a key value pair. Key is the name of the bean and value is a collection, which contains the following information:

- scope: Bean Scope of
- type: Bean of Java type
- reource: class The specific path of the file
- dependencies: Dependent Bean name
  • /Configprops: this endpoint is used to obtain the attribute information report configured in the application. From the following fragment of the endpoint return example, we can see that the configuration information about the SMS is returned. The prefix attribute represents the configuration prefix of the attribute, and the properties represent the name and value of each attribute. Therefore, we can see the configuration path of each attribute through the report. For example, if we want to close the endpoint, we can use endpoints configprops. Enabled = false to complete the setting.
  • /env: this endpoint is different from / configprops. It is used to obtain all available environment attribute reports of the application. Including: environment variables, JVM properties, application configuration, and parameters in the command line. From the example fragment returned by the endpoint below, we can see that it not only returns the configuration properties of the application, but also returns rich configuration information such as system properties and environment variables, including configurations that have not been used by the application. Therefore, it can help us easily see the configuration information that can be loaded by the current application, and introduce them into our application with the @ ConfigurationProperties annotation. In addition, in order to configure the security of attributes, the endpoint will protect the privacy of some sensitive information such as passwords, but we need to include keywords such as password, secret and key in the attribute name, so that the endpoint will use * instead of the actual attribute value when returning them.
  • /mappings: this endpoint is used to return the controller mapping relationship report of all spring MVCs. From the following example fragment, we can see that the information of the report is similar to the log information output when we enable the Web application of Spring MVC. The bean attribute identifies the request processor of the mapping relationship, and the method attribute identifies the specific processing class and processing function of the mapping relationship.
  • /Info: this endpoint is used to return some application customized information. By default, the endpoint will only return an empty json content. We can in application Some properties are set through the info prefix in the properties configuration file

Metrics class

  • /Metrics: this endpoint is used to return various important metrics of the current application, such as memory information, thread information, garbage collection information, etc.
{
	names: [
		"http.server.requests",
		"jvm.buffer.count",
		"jvm.buffer.memory.used",
		"jvm.buffer.total.capacity",
		"jvm.classes.loaded",
		"jvm.classes.unloaded",
		"jvm.gc.live.data.size",
		"jvm.gc.max.data.size",
		"jvm.gc.memory.allocated",
		"jvm.gc.memory.promoted",
		"jvm.gc.pause",
		"jvm.memory.committed",
		"jvm.memory.max",
		"jvm.memory.used",
		"jvm.threads.daemon",
		"jvm.threads.live",
		"jvm.threads.peak",
		"jvm.threads.states",
		"logback.events",
		"process.cpu.usage",
		"process.files.max",
		"process.files.open",
		"process.start.time",
		"process.uptime",
		"system.cpu.count",
		"system.cpu.usage",
		"system.load.average.1m",
		"tomcat.sessions.active.current",
		"tomcat.sessions.active.max",
		"tomcat.sessions.alive.max",
		"tomcat.sessions.created",
		"tomcat.sessions.expired",
		"tomcat.sessions.rejected"
	]
}

The key is listed above. You can view the detailed data by adding the key after the link. For example, if you want to know the JVM memory usage, visit http://localhost:8080/actuator/metrics/jvm.memory.used , the results are as follows:

{
	name: "jvm.memory.used",
	description: "The amount of used memory",
	baseUnit: "bytes",
	measurements: [
		{
			statistic: "VALUE",
			value: 108388088
		}
	],
	availableTags: [
		{
			tag: "area",
			values: [
				"heap",
				"nonheap"
			]
		},
		{
			tag: "id",
			values: [
				"Compressed Class Space",
				"PS Survivor Space",
				"PS Old Gen",
				"Metaspace",
				"PS Eden Space",
				"Code Cache"
			]
		}
	]
}

When customizing scalar values, springboot1 5. X supported org springframework. boot. actuate. metrics. Counterservice and org springframework. boot. actuate. metrics. Gaugeservice is no longer supported. Use annotation instead. Namely:
@Operations on Endpoint, @ WebEndpoint, or @ EndpointWebExtension will be automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux.
Write the code as follows:

import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
@WebEndpoint(id = "testEndpoint")
public class HelloController {

    @ReadOperation
    public HashMap<String, Object> index() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", "sky");
        hashMap.put("age", 24);
        return hashMap;
    }
}

You can access http://localhost:8080/actuator/testEndpoint , the results are as follows:

{
	name: "sky",
	age: 24
}
  • /Health: we have used this endpoint in the initial example. It is used to obtain various health indicator information of the application. In the spring boot starter actor module, some health indicator detectors of common resources are implemented.

Operation control class

In the native endpoint, only one endpoint is provided to close the application: / shutdown. We can enable it through the following configuration:

management.endpoint.shutdown.enabled=true

After the above properties are configured, you only need to access the / shutdown endpoint of the application to realize the remote operation of closing the application. Since the operation of opening and closing applications is a very dangerous thing, we need to add a certain protection mechanism when we really use them online.

Topics: Java Spring Spring Boot