Article for Spring Boot service monitoring, health checks, thread information, JVM heap information, metrics collection, monitor the operation! ...

Author |  Richard_Yi

 Zebian | Xu Veyron

Manuscripts | Nuggets

Cover photo | CSDN download the visual China

This article is the author's personal experience, for your reference.

Last year we did a project in transition micro Services Architecture 1.0, but this service monitoring has not kept pace. This does not, recently I was assigned the task you want to service our core micro-monitoring applications all together. Our micro-service applications are SpringBoot application, and therefore naturally think of Actuator With Spring Boot module.

Benpian after I complete this work order, summarize learning applications for Spring Boot Actuator module. In this article, you can learn to:

1. Getting started quickly using Spring Boot Actuator of
2, some of the important endpoints of Spring Boot Actuator introduction of
3, how to view real-time thread dump information currently applied by Actuator module
4, how to view the heap information about the current application in real time by Actuator Module
5, how to print the log level of the current real-time changes applied by Actuator module
6, ...

Then I will introduce:

TODO: SpringBoot micro-services application integration to achieve Prometheus + Grafana Monitoring Alarms

What is Spring Boot Actuator

Spring Boot Actuator module provides production-level features, such as health checks, audits, metrics collection, HTTP tracking, help us monitor and manage Spring Boot application, Bean loading conditions, environment variables, log information, thread information, JVM heap information . This module is a collection of information within the application module is exposed to the outside, the above-described functions can be accessed via HTTP and JMX.

Because exposure characteristics of inside information, Actuator can also be some external application monitoring and system integration (Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic, etc.). These monitoring systems provide excellent dashboards, graphs, analysis and alerts to help you through a unified user-friendly interface, monitor and manage your applications.

Actuator use Micrometer integration with these external application monitoring system. As a result, with little configuration can easily integrate external monitoring system.

Micrometer provides a common API to collect performance data on the Java platform, applications only need to use Micrometer common API to collect performance metrics can be. Micrometer will be responsible for completing the work of adaptation to different monitoring systems. This makes the switch monitoring system easy.

The contrast Slf4j located in the Java Logger.

Quick start, create a Spring Boot Actuator Demo

Let's create a demo application.

You can create by Spring Boot CLI:

spring init -d=web,actuator -n=actuator-demo actuator-demo

Or create by Spring Initializr:

Corresponding maven dependency:

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

Corresponding Gradle dependency:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-actuator")
}

Endpoints Introduction

Spring Boot provides a so-called endpoints (endpoint translation below) to access and interact with the application to the outside.

Analogy, the /healthendpoint provides some basic information about the health of the application. metricsEndpoint provides some useful applications index (JVM memory usage, CPU usage systems, etc.).

These Actuator module already has an endpoint which we call primary endpoint. According to the role of the endpoint, we can be divided into three categories:

Application configuration class: obtain configuration information category is closely related to the Spring Boot application application loading the application configuration, environment variables, automated configuration reports.

Metrics categories: acquisition application is running for monitoring metrics, such as: memory information, thread pool information, HTTP request statistics.

Operation control class: Providing the close of the application and other operations based functions.

Detailed native endpoint descriptions, please refer to the official website prevail, not repeat them here inviting space.

It should be noted that:

1, each endpoint may be configured individually disabled or initiated by

2, different from the Actuator 1.x, most endpoint Actuator 2.x default swap banned . The default endpoint Actuator 2.x increases the /actuatorprefix. Two endpoints exposed to default /actuator/healthand/actuator/info


Endpoint exposed configuration

We can through the following configuration to configure HTTP exposed via JMX and endpoints.

Property Default
management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include *
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include info,healt

It can open all monitoring points

management.endpoints.web.exposure.include=*

Section can also choose to open, "*" denotes all endpoints exposed, if multiple endpoints specified with "," separate

management.endpoints.web.exposure.exclude=beans,trace

Actuator default path all monitoring points are /actuator/*, of course, if there is need this path also supports custom.

management.endpoints.web.base-path=/minitor

After setting the restart, again becomes accessible address /minitor/*.

We now configured as follows:

# "*" 代表暴露所有的端点 如果指定多个端点,用","分开
management.endpoints.web.exposure.include=*
# 赋值规则同上
management.endpoints.web.exposure.exclude=

DEMO Start program, visit http://localhost:8080/actuator, exposed to view endpoint:


Such shown above is because JSON-handle chrome browser plug-in installed, in fact, a large section of the return json

Below, I'll highlight some of the more important endpoints.

Important endpoint resolution

5.1  /healthEndpoint

/healthThe endpoint health indicators polymerization your program to check the health of the program. Endpoint public health information application depends on:

management.endpoint.health.show-details=always

This attribute can be configured to use one of the following values:

Name Description
never Does not show detailed information, up or down state, the default configuration
when-authorized Details will be presented to the user through authentication. Role authorization can be  management.endpoint.health.rolesconfigured
always Details of exposure for all users

According to the above configuration, configured alwaysAfter that, we started the project, access to http://localhost:8080/actuator/healththe port, you can see this information:

Health information is not feeling like a bit less? Do not worry, it is because we are creating a basis for most of the Demo project not depends on many components.

/healthThere are many auto-configuration of the endpoint health indicator: as redis, rabbitmq, db and other components. When you have the dependency item corresponding components when the health indicator is automatically assembled, and then information corresponding to the acquisition. As above diskSpace node information is DiskSpaceHealthIndicatorat work.

Above screenshot is taken from official documents

This is my another project of /healthendpoint information.

When the above assembly has an abnormal state, that is, the whole state of the application and services down. We can also disable the health monitoring of a component through configuration.

management.health.mongo.enabled: false

Or disable all automatic configuration health indicators:

management.health.defaults.enabled: false

⭐ Custom Health Indicator

Of course, you can also customize a Health Indicator, only need to implement HealthIndicatorinterfaces or extend AbstractHealthIndicatorclasses.

/**
 * @author Richard_yyf
 * @version 1.0 2020/1/16
 */
@Component
publicclassCustomHealthIndicatorextendsAbstractHealthIndicator{
@Override
protectedvoid doHealthCheck(Health.Builder builder) throwsException{
// 使用 builder 来创建健康状态信息
// 如果你throw 了一个 exception,那么status 就会被置为DOWN,异常信息会被记录下来
        builder.up()
.withDetail("app", "这个项目很健康")
.withDetail("error", "Nothing, I'm very good");
}
}

final effect:

5.2  /metricsEndpoint

/metricsEndpoint is used to return the current application range of important metrics, such as: memory information, thread information, garbage collection information, tomcat, database connection pools.

{
"names": [
"tomcat.threads.busy",
"jvm.threads.states",
"jdbc.connections.active",
"jvm.gc.memory.promoted",
"http.server.requests",
"hikaricp.connections.max",
"hikaricp.connections.min",
"jvm.memory.used",
"jvm.gc.max.data.size",
"jdbc.connections.max",
....
]
}

Different from 1.x, Actuator can not see specific targets information in this interface, just shows a list of indicators. In order to obtain detailed information on a particular index, we can request information on specific targets, like this:

http://localhost:8080/actuator/metrics/{MetricName}

For example, I visit /actuator/metrics/jvm.memory.max, return information is as follows:

You can also use the query param ways to view a separate area. For example, you can access /actuator/metrics/jvm.memory.max?tag=id:Metaspace. The result is:

5.3  /loggersEndpoint

/loggersEndpoint exposes information about all of our internal procedures logger configuration. We visit /actuator/loggersyou can see,

You can also access a single logger in the following manner,

http://localhost:8080/actuator/loggers/{name}

For example, I now visit rootlogger,http://localhost:8080/actuator/loggers/root

{
"configuredLevel": "INFO",
"effectiveLevel": "INFO"
}

⭐ change the log level at runtime

/loggersI would like to mention most endpoint is this feature, you can dynamically modify the log level.

For example, we can modify the following manner rootlogger log level. We just need to initiate a URL for http://localhost:8080/actuator/loggers/rootthe POSTrequest, POST message is as follows:

{
"configuredLevel":
"DEBUG"
}

Think about it, this feature is not very useful. If in a production environment, you want your application Debug output of some information in order to diagnose some anomalies in you, you, you just need to be modified as described above, without the need to restart the application.

If you want to reset to default, the value change null

5.4  /infoEndpoint

/infoEndpoints can be used to display information about your program. I understand that some of the basic information of the program over. And you can follow their own needs in the configuration file application.propertiesin the customized configuration (by default, the endpoint will return an empty json content.):

info.app.name=actuator-test-demo
info.app.encoding=UTF-8
info.app.java.source=1.8
info.app.java.target=1.8
# 在 maven 项目中你可以直接用下列方式引用 maven properties的值
# [email protected]@
# [email protected]@
# [email protected]@

Start the project, visit http://localhost:8080/actuator/info:

{
"app": {
"encoding": "UTF-8",
"java": {
"source": "1.8.0_131",
"target": "1.8.0_131"
},
"name": "actuator-test-demo"
}
}

5.5  /beansEndpoint

/beansSpring terminal returns all bean container alias, type, whether a single embodiment, dependency information.

Visit http://localhost:8080/actuator/beans, returns the following:

5.6  /heapdump Endpoint

Access: http://localhost:8080/actuator/heapdumpautomatically generates a file Jvm heap of heapdump. We can use the JDK that comes with Jvm monitoring tool VisualVM open this file to view a memory snapshot .

5.7  /threaddump Endpoint

I personally feel that this endpoint is particularly useful, convenient and we see the thread when the daily positioning problem. The main show thread name, state of the thread ID, thread, whether to wait for lock resources, such as thread stack information. It is possible to see less intuitive. Access http://localhost:8080/actuator/threaddumpreturns the following:

5.8  /shutdownEndpoint

The endpoints belong to the operation control based endpoint, gracefully close Spring Boot application. To use this feature you first need to open the configuration file:

management.endpoint.shutdown.enabled=true

Since the shutdown interface defaults to only support POST requests , we start the Demo project, to http://localhost:8080/actuator/shutdowninitiate POSTthe request. returned messages:

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

Then the application is closed.

Due to the open close operation of the application itself is a very dangerous thing, so the real online use, we need to join them some protection mechanisms, such as: custom path Actuator endpoints, integrating Spring Security for security check and so on. (Not particularly necessary, do not open this endpoint)

Spring Security integration for endpoint security check

Since the information generated by interaction endpoints and are very sensitive to the need to prevent unauthorized external access. If your application exists in Spring Security dependency, when using the default HTTP-based authentication forms to protect endpoints.

If not, just add the corresponding dependencies to:

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

After the addition, we need to define security validation rules to override the default configuration of Spring Security.

Here I give two versions of the template configuration:

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 * @author Richard_yyf
 */
@Configuration
publicclassActuatorSecurityConfigextendsWebSecurityConfigurerAdapter{
/*
     * version1:
     * 1. 限制 '/shutdown'端点的访问,只允许ACTUATOR_ADMIN访问
     * 2. 允许外部访问其他的端点
     * 3. 允许外部访问静态资源
     * 4. 允许外部访问 '/'
     * 5. 其他的访问需要被校验
     * version2:
     * 1. 限制所有端点的访问,只允许ACTUATOR_ADMIN访问
     * 2. 允许外部访问静态资源
     * 3. 允许外部访问 '/'
     * 4. 其他的访问需要被校验
     */
@Override
protectedvoid configure(HttpSecurity http) throwsException{
// version1
//        http
//                .authorizeRequests()
//                    .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
//                        .hasRole("ACTUATOR_ADMIN")
//                .requestMatchers(EndpointRequest.toAnyEndpoint())
//                    .permitAll()
//                .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
//                    .permitAll()
//                .antMatchers("/")
//                    .permitAll()
//                .antMatchers("/**")
//                    .authenticated()
//                .and()
//                .httpBasic();
// version2
        http
.authorizeRequests()
.requestMatchers(EndpointRequest.toAnyEndpoint())
.hasRole("ACTUATOR_ADMIN")
.requestMatchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll()
.antMatchers("/")
.permitAll()
.antMatchers("/**")
.authenticated()
.and()
.httpBasic();
}
}

application.propertiesThe configuration is as follows:

# Spring Security Default user name and password
spring.security.user.name=actuator
spring.security.user.password=actuator
spring.security.user.roles=ACTUATOR_ADMIN

Original link:

https://juejin.im/post/5e2179def265da3e152d2561

推荐阅读:从零单排HBase 02:全面认识HBase架构(建议收藏)
11 国股市熔断,“祸及”程序员?!
云原生就一定安全吗?
和黑客斗争的 6 天!
用 3 个“鸽子”,告诉你闪电网络是怎样改变加密消息传递方式的!
想成为一个数据科学家却不知道从何下手?这份路线图带你打开数据科学大门!
真香,朕在看了!
Published 280 original articles · won praise 1245 · Views 1.18 million +

Guess you like

Origin blog.csdn.net/FL63Zv9Zou86950w/article/details/104890016