Detailed Explanation of Actuator Monitoring Endpoint of Spring Boot Knowledge Collection


insert image description here

0. Preface

Background: I have been using various components and features of Spring Boot sporadically, and have never studied and summarized systematically. This time I take this opportunity to make a wave. Learn together and make progress together. Ha ha

Spring Boot Actuator is a powerful monitoring and management framework that provides a series of monitoring endpoints that can be used to obtain application status, metrics, health checks, configuration information, and more. Actuator's monitoring endpoints can be accessed via HTTP requests and return responses with information about the application's runtime.

Use Actuator to easily understand the health of your application, monitor key metrics, and take appropriate action as needed. It provides developers and operators with an easy and efficient way to monitor and manage Spring Boot applications.

This series of articles will dive into various aspects of monitoring endpoints with Spring Boot Actuator. We will walk through the default monitoring endpoints one by one, including health checks, information, metrics, etc., and explain how to customize and extend these endpoints to meet specific needs.

In this series of articles, you will learn the following:

  1. Introduction and basic concepts of Actuator.
  2. Detailed explanation of the default monitoring endpoints, including health checks, information, metrics, etc.
  3. How to customize monitoring endpoints to get specific application status and information.
  4. Monitor the security configuration of endpoints to protect access to sensitive information.
  5. How to use Actuator's event and listener functionality.
  6. Actuator's extensibility mechanism, including custom indicators, custom endpoints and custom EndpointGroup, etc.

By reading this series of articles, you will have a comprehensive understanding of the functions and usage of Spring Boot Actuator monitoring endpoints, and you will be able to flexibly use Actuator to monitor and manage your Spring Boot applications. Let's start this fun and practical learning journey!

1. Reference documents

  1. Spring Boot Actuator Tutorial

    Tutorialspoint It is still a relatively good and authoritative website. Some of the examples listed above are of good reference value, at least much better than some code examples on CSDN, they will not be copied, even the bugs are exactly the same, haha. It is recommended that you can browse casually, the things are still quite complete. The link above introduces the basic concepts and usage of Spring Boot Actuator, including default endpoints, custom endpoints, health checks, etc., and provides some sample code.
    insert image description here

  2. Official Documentation - Spring Boot Actuator

The official documentation provides detailed instructions on Actuator, including an overview of monitoring endpoints, an introduction to default endpoints, creation and configuration of custom endpoints, and more.

  1. Official Documentation - Health Indicator

    The section on Health Indicator in the official documentation describes how to create custom health check indicators, and provides some examples and descriptions of configuration options.

  2. Baeldung - A Guide to Spring Boot Actuator

    The article on the Baeldung website provides a comprehensive Spring Boot Actuator guide, covering the core concepts of Actuator, detailed explanations of monitoring endpoints, and how to customize and configure endpoints.

2. Basic introduction

spring-boot-starter-actuatoris a module provided by Spring Boot for monitoring and managing runtime information of Spring Boot applications. It provides a set of monitoring endpoints (endpoints) for obtaining application health status, performance indicators, configuration information, etc., and supports access via HTTP or JMX.

Here are spring-boot-starter-actuatorsome key features and capabilities of :

  1. Health Indicators : spring-boot-starter-actuatorProvides a health endpoint that can be used to check the health of the application. It provides a set of predefined health check rules through Health Indicator, such as database connection, disk space, memory usage, etc. You can also customize Health Indicator to add custom health check rules.

  2. Info Endpoint (Info Endpoint) : This endpoint is used to obtain custom information for the application. Metadata of the application, such as version number, build information, etc., can be configured and exposed through the Info Endpoint.

  3. Metrics : spring-boot-starter-actuatorSupports collecting and exposing application metrics, such as CPU usage, memory usage, request processing time, etc. You can use the Micrometer library to collect and manage metrics and expose them through the Metrics Endpoint.

  4. Configuration Properties : This feature allows retrieval and adjustment of application configuration properties. The configuration properties of the application can be viewed and modified through the Configuration Properties Endpoint, and dynamic refresh of the properties is supported.

  5. Logging : spring-boot-starter-actuatorProvides an endpoint for managing application logging levels. You can view and modify the logger level and reload the logging configuration through the Logging Endpoint.

  6. Remote Shell (Remote Shell) : This feature allows connecting to the application via SSH or Telnet and performing some administrative operations. Remote Shell can be enabled in the application to remotely manage and monitor the application through the command line interface.

spring-boot-starter-actuatorThe above functionality can be easily integrated into a Spring Boot application by introducing dependencies. At the same time, spring-boot-starter-actuatorsome security configuration options are provided to ensure secure access to monitoring endpoints.

Endpoints supported by default

Spring Boot provides the following commonly used endpoints by default:
insert image description here

  1. /actuator/health : Displays the health status of the application. Returns a JSON response representing the health status.
    Suppose our application is an e-commerce platform, showing /actuator/healththe health status of endpoints and other custom health check items:
{
    
    
  "status": "UP",
  "components": {
    
    
    "database": {
    
    
      "status": "UP",
      "details": {
    
    
        "connection": "OK",
        "activeConnections": 10
      }
    },
    "storage": {
    
    
      "status": "UP",
      "details": {
    
    
        "availableSpace": "10 GB",
        "usedSpace": "2 GB"
      }
    },
    "paymentGateway": {
    
    
      "status": "DOWN",
      "details": {
    
    
        "error": "Connection timeout"
      }
    }
  }
}
  1. /actuator/info : Displays application information.

  2. /actuator/metrics : Displays application metrics. Returns things like memory usage, HTTP request count, etc.

  3. /actuator/beans : Displays all Spring Beans in the application. Returns a JSON response containing all beans.
    insert image description here

  4. /actuator/env : Displays the application's environment properties. Returns a JSON response containing application environment properties such as profile properties, system properties, etc.

  5. /actuator/mappings : Displays URL mappings for the application. Returns a JSON response containing information about all URL mappings in the application, including controllers, request methods, etc.

  6. /actuator/trace : Displays recent HTTP request trace information. Returns a JSON response containing the most recent HTTP request, including request method, URL, status code, etc.

{
    
    
  "traces": [
    {
    
    
      "timestamp": "2023-08-15T09:26:18.062Z",
      "principal": null,
      "session": null,
      "request": {
    
    
        "method": "GET",
        "uri": "http://localhost:8001/actuator/loggers",
        "headers": {
    
    
          "accept": [
            "application/vnd.spring-boot.actuator.v2+json"
          ],
          "host": [
            "localhost:8001"
          ],
          "connection": [
            "Keep-Alive"
          ],
          "user-agent": [
            "Apache-HttpClient/4.5.14 (Java/17.0.7)"
          ],
          "accept-encoding": [
            "br,deflate,gzip,x-gzip"
          ]
        },
        "remoteAddress": null
      },
      "response": {
    
    
        "status": 200,
        "headers": {
    
    
          "Access-Control-Allow-Origin": [
            "*"
          ],
          "Access-Control-Allow-Credentials": [
            "true"
          ],
          "Access-Control-Allow-Methods": [
            "GET,POST,OPTIONS,PUT,DELETE"
          ],
          "Content-Type": [
            "application/vnd.spring-boot.actuator.v2+json;charset=UTF-8"
          ],
          "Transfer-Encoding": [
            "chunked"
          ],
          "Date": [
            "Tue, 15 Aug 2023 09:26:18 GMT"
          ]
        }
      },
      "timeTaken": 49
    },
    {
    
    
      "timestamp": "2023-08-15T09:24:19.108Z",
      "principal": null,
      "session": null,
      "request": {
    
    
        "method": "GET",
        "uri": "http://localhost:8001/actuator/beans",
        "headers": {
    
    
          "accept": [
            "application/vnd.spring-boot.actuator.v2+json"
          ],
          "host": [
            "localhost:8001"
          ],
          "connection": [
            "Keep-Alive"
          ],
          "user-agent": [
            "Apache-HttpClient/4.5.14 (Java/17.0.7)"
          ],
          "accept-encoding": [
            "br,deflate,gzip,x-gzip"
          ]
        },
        "remoteAddress": null
      },
      "response": {
    
    
        "status": 200,
        "headers": {
    
    
          "Access-Control-Allow-Origin": [
            "*"
          ],
          "Access-Control-Allow-Credentials": [
            "true"
          ],
          "Access-Control-Allow-Methods": [
            "GET,POST,OPTIONS,PUT,DELETE"
          ],
          "Content-Type": [
            "application/vnd.spring-boot.actuator.v2+json;charset=UTF-8"
          ],
          "Transfer-Encoding": [
            "chunked"
          ],
          "Date": [
            "Tue, 15 Aug 2023 09:24:19 GMT"
          ]
        }
      },
      "timeTaken": 70
    },
    {
    
    
      "timestamp": "2023-08-15T09:23:50.737Z",
      "principal": null,
      "session": null,
      "request": {
    
    
        "method": "GET",
        "uri": "http://localhost:8001/actuator/health",
        "headers": {
    
    
          "accept": [
            "application/vnd.spring-boot.actuator.v2+json"
          ],
          "host": [
            "localhost:8001"
          ],
          "connection": [
            "Keep-Alive"
          ],
          "user-agent": [
            "Apache-HttpClient/4.5.14 (Java/17.0.7)"
          ],
          "accept-encoding": [
            "br,deflate,gzip,x-gzip"
          ]
        },
        "remoteAddress": null
      },
      "response": {
    
    
        "status": 200,
        "headers": {
    
    
          "Access-Control-Allow-Origin": [
            "*"
          ],
          "Access-Control-Allow-Credentials": [
            "true"
          ],
          "Access-Control-Allow-Methods": [
            "GET,POST,OPTIONS,PUT,DELETE"
          ],
          "Content-Type": [
            "application/vnd.spring-boot.actuator.v2+json;charset=UTF-8"
          ],
          "Transfer-Encoding": [
            "chunked"
          ],
          "Date": [
            "Tue, 15 Aug 2023 09:23:51 GMT"
          ]
        }
      },
      "timeTaken": 488
    }
  ]
}
响应文件已保存。
> 2023-08-15T172634.200.json

Response code: 200; Time: 38ms (38 ms); Content length: 2230 bytes (2.23 kB)

  1. /actuator/auditevents : Displays audit events for the application. Returns a JSON response containing application audit events, such as login success, failure, etc.

  2. /actuator/loggers : Display and modify the application's logger configuration. Returns a JSON response containing logger configuration information, which can modify the logger level.

  3. /actuator/httptrace : Displays recent HTTP trace information. Returns a JSON response containing trace information for the most recent HTTP request and response, including request and response headers, status code, etc.

  4. /actuator/threaddump : Displays thread dump information for applications. Returns a JSON response containing application thread dump information for analysis of thread status and problems.

大家可以在自己的项目中去尝试获取一下这些信息,此处不再演示。, let's continue.

3. Steps

3.1. Introducing dependencies

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

3.2. Configuration file

You can configure these configurations according to your needs. Another point is that opening the endpoint has certain security risks. You can see from the results I demonstrated above that it will actually output some core information and provide value to attackers.Remember that the production environment should not be opened unless it is necessary

 # Actuator Endpoints
# 启用所有端点,默认为true
management.endpoints.enabled-by-default=true
# 管理端点的基本路径,默认为/actuator
management.endpoints.web.base-path=/actuator
# 配置需要暴露的端点,*表示全部暴露
management.endpoints.web.exposure.include=*
# 配置需要排除的端点,如果需要排除特定端点,可以在此处指定
management.endpoints.web.exposure.exclude=
# 允许跨域访问的来源,*表示允许全部来源
management.endpoints.web.cors.allowed-origins=*
# 允许跨域访问的HTTP方法
management.endpoints.web.cors.allowed-methods=GET

# Health Endpoint
# 显示详细的健康状态信息,always表示始终显示
management.endpoint.health.show-details=always

# Info Endpoint
# 应用程序名称
info.app.name=我的应用程序
# 应用程序版本
info.app.version=1.0.0

# Metrics Endpoint
# 启用度量指标端点
management.endpoint.metrics.enabled=true
# 启用缓存的度量指标
management.endpoint.metrics.cache.enabled=true
# 启用默认的度量指标
management.metrics.export.defaults.enabled=true

# Beans Endpoint
# 启用显示所有 Spring Bean 的端点
management.endpoint.beans.enabled=true

# Environment Endpoint
# 启用显示应用程序环境属性的端点
management.endpoint.env.enabled=true

# Mappings Endpoint
# 启用显示应用程序 URL 映射信息的端点
management.endpoint.mappings.enabled=true

# Trace Endpoint
# 启用显示最近的 HTTP 请求跟踪信息的端点
management.endpoint.trace.enabled=true

# Auditevents Endpoint
# 启用显示应用程序审计事件的端点
management.endpoint.auditevents.enabled=true

# Loggers Endpoint
# 启用显示和修改应用程序日志记录器配置的端点
management.endpoint.loggers.enabled=true

# Httptrace Endpoint
# 启用显示最近的 HTTP 请求和响应跟踪信息的端点
management.endpoint.httptrace.enabled=true

# Threaddump Endpoint
# 启用显示应用程序线程转储信息的端点
management.endpoint.threaddump.enabled=true

3.3. Core source code

Its core code includes the following key components and functions: Different versions have different classes and interfaces, including the above configuration items. This article is based on2.0.3

  1. Endpoint interface : EndpointThe interface defines the core methods for monitoring and management functions. All monitoring endpoints must implement this interface and provide their own logic implementation.

  2. MetricsEndpoint class : MetricsEndpointis a monitoring endpoint used to provide application metrics information. It inherits from AbstractEndpointand implements Endpointthe methods of the interface, by collecting the application's metric data and returning it to the caller.

  3. InfoEndpoint class : InfoEndpointis a monitoring endpoint for providing custom information about the application. It inherits from AbstractEndpointand implements Endpointthe methods of the interface, by collecting custom information about the application and returning it to the caller.

  4. ControllerEndpointHandlerMapping class : EndpointHandlerMappingThe class is a Spring MVC processor mapper responsible for mapping HTTP requests to the corresponding monitoring endpoint processors.
    insert image description here

  5. EndpointWebMvcManagementContextConfiguration class : EndpointWebMvcManagementContextConfigurationThe class is the automatic configuration class of Spring Boot Actuator, which is used to register and configure the core components of Actuator, including EndpointHandlerMapping, EndpointMvcAdapteretc.

  6. AbstractEndpoint class : AbstractEndpointThe class is Endpointthe abstract implementation of the interface, which provides some common functions and methods, such as the ID of the endpoint, whether it is enabled, security configuration, etc. Custom monitoring endpoints can inherit from this class to simplify implementation.

  7. HealthIndicator : It is a core interface provided by Spring Boot Actuator, which is used to define the health check logic of the application. It allows developers to customize the implementation of the health check and register it as a Spring Bean, making it part of the Actuator. .
    insert image description here
    We can see that there are so many agreed upon configurations that have been added to the health check.
    HealthIndicatorInterface is a core interface provided by Spring Boot Actuator, which is used to define the health check logic of the application. It allows developers to customize the implementation of the health check and register it as a Spring Bean, making it part of the Actuator.
    HealthIndicatorThe interface has only one method health(), which returns a Healthobject representing the health status of the application.
    To implement a custom health indicator, you need to implement HealthIndicatorthe interface and implement health()the method in it. In this method, developers can write their own health check logic and return a Healthobject that describes the health status of the application.
    HealthObjects can be created using static methods such as Health.up(), Health.down(), and so on. Health.unknown()It can contain some status information, error messages, exception information, etc. to provide a more detailed description of the health status.

A simple implementation is as follows:

@Component
public class MyHealthIndicator implements HealthIndicator {
    
    

    @Override
    public Health health() {
    
    
        // 自定义健康检查逻辑
        boolean isHealthy = checkHealth(); // 健康检查的具体实现

        if (isHealthy) {
    
    
            return Health.up().build(); // 返回健康状态
        } else {
    
    
            return Health.down().withDetail("Error", "Something went wrong").build(); // 返回不健康状态,并提供错误信息
        }
    }

    private boolean checkHealth() {
    
    
        // 实现自定义的健康检查逻辑
        // 返回 true 表示健康,返回 false 表示不健康
        // 可以根据具体需求进行判断
    }
}

4. Example project

Suppose we have a Spring Boot application which uses MongoDB as the database and we want to add a custom health check rule to check the connection status to the MongoDB database. If the connection is fine, the application will be marked as healthy, otherwise it will be marked as unhealthy.

First, we need to create a custom health indicator class MongoDBHealthIndicator, implement HealthIndicatorthe interface, and override health()the method to perform a health check of the MongoDB connection.
We use MongoClientthe object to execute the MongoDB ping command. If the command is executed successfully, it is considered that the connection with the database is normal. If there is an exception, we add the error message to the details of the health status.

import com.mongodb.MongoClient;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class MongoDBHealthIndicator implements HealthIndicator {
    
    

    private final MongoClient mongoClient;

    public MongoDBHealthIndicator(MongoClient mongoClient) {
    
    
        this.mongoClient = mongoClient;
    }

    @Override
    public Health health() {
    
    
        try {
    
    
            mongoClient.getDatabase("admin").runCommand("ping"); // 执行 MongoDB 的 ping 命令,检查连接状态
            return Health.up().build(); // 健康状态
        } catch (Exception e) {
    
    
            return Health.down().withDetail("Error", e.getMessage()).build(); // 非健康状态,添加错误信息
        }
    }
}

Then, make sure the application can automatically scan for MongoDBHealthIndicatorthe class. Automatic scanning can be done using @ComponentScanor annotations.@SpringBootApplication

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(MyApplication.class, args);
    }
}

Finally, start the application and access /actuator/healththe endpoint to view the results of the custom health check rules.

GET /actuator/health

You should be able to see the custom health check results in the returned JSON, similar to the following output:
mongoDBIndicates the result of the custom health check, statusthe field is for "UP"the health status, and detailsthe field is for additional details. If there is a problem with the connection, statusthe field will change to "DOWN", with detailsan error message in the field.

{
    
    
  "status": "UP",
  "components": {
    
    
    "mongoDB": {
    
    
      "status": "UP",
      "details": {
    
    
        "error": null
      }
    },
    "ping": {
    
    
      "status": "UP",
      "details": {
    
    
        "error": null
      }
    }
  }
}

5. Summary

The Spring Boot Actuator is designed to provide an easy, extensible and configurable way to monitor and manage Spring Boot applications.

  1. Convention is better than configuration : Spring Boot Actuator follows Spring Boot's convention over configuration principle. Through default configuration and automatic assembly, the monitoring and management endpoints can be automatically available when the application starts without cumbersome manual configuration.

  2. Modularity and extensibility of endpoints : Actuator provides a set of core endpoints (such as health checks, information, metrics, etc.), and also supports the addition and extension of custom endpoints. Developers can write custom endpoints according to their own needs, and integrate them into Actuator through simple configuration.

  3. HTTP-based remote access : Actuator's endpoints are accessed via the HTTP protocol, which enables monitoring and management operations to be performed remotely without direct access to the application's code or runtime environment. This makes it easy to monitor and manage multiple applications in a distributed environment.

  4. Provides rich monitoring and management capabilities : Actuator provides a series of powerful endpoints to monitor and manage various aspects of the application, including health status, performance indicators, environment properties, logger configuration, and more. These features can help developers quickly understand the health of the application and perform troubleshooting and performance optimization.

  5. Security and permission control : Actuator provides security configuration options to restrict access to endpoints, ensuring that only authorized users or roles can access sensitive monitoring and management endpoints. This protects the security of applications and the confidentiality of sensitive information.

Guess you like

Origin blog.csdn.net/wangshuai6707/article/details/132303140