Spring Boot包含许多附加功能,可帮助您在将应用程序推送到生产环境中时对其进行监控和管理。您可以选择使用HTTP端点或JMX来管理和监视您的应用程序。审核、运行状况和指标收集也可以自动应用于您的应用程序。

1. Enabling Production-ready Features

spring-boot-actuator模块提供了Spring Boot的所有可投入生产的特性。启用这些特性的推荐方法是在Spring-ot-starter-starator“starter”上添加一个依赖项。

Definition of Actuator

执行器是一个制造术语,指的是用于移动或控制某物的机械设备。执行器可以从一个小的变化产生大量的运动。

要将执行器添加到基于Maven的项目中,请添加以下‘starter’依赖项:

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

对于Gradle,请使用以下声明:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
}
           
           

2. Endpoints

执行器端点允许您监控应用程序并与其交互。Spring Boot包括许多内置终结点,并允许您添加自己的终结点。例如,Health终结点提供基本的应用程序运行状况信息。

您可以启用或禁用每个端点,并通过HTTP或JMX公开它们(使它们可远程访问)。当端点同时处于启用和公开状态时,该端点被视为可用。只有当内置终端可用时,才会自动配置它们。大多数应用程序选择暴露而不是HTTP,在HTTP中,端点的ID和前缀/Actuator被映射到一个URL。例如,默认情况下,Health终结点被映射到/Actuator/Health

To learn more about the Actuator’s endpoints and their request and response formats, see the separate API documentation (HTML or PDF).

以下与技术无关的终端可用:

ID Description

审核事件

显示当前应用程序的审核事件信息。需要AuditEventRepositoryBean。

Bean

显示应用程序中所有SpringBean的完整列表。

缓存

显示可用缓存。

条件

显示在配置类和自动配置类上评估的条件以及它们匹配或不匹配的原因。

配置属性

显示所有@ConfigurationProperties的排序列表。

环境

公开来自Spring的ConfigurableEnvironment的属性。

飞行通道

显示已应用的任何Flyway数据库迁移。需要一个或多个FlywayBean。

健康

显示应用程序运行状况信息。

HTTPS

显示HTTP交换信息(默认情况下,最近100个HTTP请求-响应交换)。需要HttpExchangeRepositoryBean。

信息

显示任意应用程序信息。

集成图

显示了Spring集成图形。需要对Spring-Integration-core的依赖。

记录器

显示和修改应用程序中记录器的配置。

液基

显示已应用的任何Liquibase数据库迁移。需要一个或多个LiquibaseBean。

指标

显示当前应用程序的“指标”信息。

映射

显示所有@Requestmap路径的排序列表。

石英

显示有关Quartz Scheduler作业的信息。

计划任务

显示应用程序中的计划任务。

会话

允许从Spring会话支持的会话存储中检索和删除用户会话。需要使用Spring会话的基于Servlet的Web应用程序。

关闭

允许应用程序正常关闭。默认情况下禁用。

启动

显示了ApplicationStartup收集的启动步骤数据。需要使用BufferingApplicationStartup配置SpringApplication

线程转储

执行线程转储。

如果您的应用程序是Web应用程序(Spring MVC、Spring WebFlux或Jersey),则可以使用以下附加端点:

ID Description

堆转储

返回堆转储文件。在HotSpot JVM上,返回HPROF格式的文件。在OpenJ9 JVM上,会返回phd格式的文件。

日志文件

返回日志文件的内容(如果已设置logging.file.namelogging.file.Path属性)。支持使用HTTPRange头来检索日志文件的部分内容。

普罗米修斯

以普罗米修斯服务器可以抓取的格式公开指标。需要依赖微米-注册表-普罗米修斯

2.1. Enabling Endpoints

默认情况下,除关闭之外的所有终结点都处于启用状态。要配置终结点的启用,请使用其management.endpoint.<;id>;.enabled属性。以下示例启用Shutdown终结点:

Properties
Yaml
management.endpoint.shutdown.enabled=true
            
            

如果您希望端点启用是选择加入而不是选择退出,请将management.endpoints.enabled-by-default属性设置为FALSE,并使用单个端点启用的属性重新选择加入。以下示例启用INFO终结点并禁用所有其他终结点:

Properties
Yaml
management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true
            
            
Disabled endpoints are removed entirely from the application context. If you want to change only the technologies over which an endpoint is exposed, use the include and exclude properties instead.

2.2. Exposing Endpoints

默认情况下,只有健康端点通过HTTP和JMX公开。由于终结点可能包含敏感信息,因此应仔细考虑何时公开它们。

要更改公开的终结点,请使用以下特定于技术的IncludeExclude属性:

Property Default

management.endpoints.jmx.exposure.exclude

management.endpoints.jmx.exposure.include

健康

management.endpoints.web.exposure.exclude

management.endpoints.web.exposure.include

健康

Include属性列出了公开的终结点的ID。Exclude属性列出不应公开的终结点的ID。Exclude属性优先于Include属性。您可以使用终结点ID列表配置IncludeExclude属性。

例如,要仅通过JMX公开Healthinfo终结点,请使用以下属性:

Properties
Yaml
management.endpoints.jmx.exposure.include=health,info
            
            

*可用于选择所有端点。例如,要通过HTTP公开除envBean终结点之外的所有内容,请使用以下属性:

Properties
Yaml
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
            
            
* has a special meaning in YAML, so be sure to add quotation marks if you want to include (or exclude) all endpoints.
If your application is exposed publicly, we strongly recommend that you also secure your endpoints.
If you want to implement your own strategy for when endpoints are exposed, you can register an EndpointFilter bean.

2.3. Security

出于安全考虑,默认情况下,只有/Health终结点通过HTTP公开。可以使用management.endpoints.web.exposure.include属性配置公开的终结点。

Before setting the management.endpoints.web.exposure.include, ensure that the exposed actuators do not contain sensitive information, are secured by placing them behind a firewall, or are secured by something like Spring Security.

如果Spring Security位于类路径上,并且不存在其他SecurityFilterChainBean,则除/Health以外的所有执行器都由Spring Boot自动配置保护。如果您定义了一个定制的SecurityFilterChainBean,那么Spring Boot自动配置就会退出,并允许您完全控制执行器访问规则。

如果您希望为HTTP端点配置自定义安全性(例如,只允许具有特定角色的用户访问它们),Spring Boot提供了一些方便的RequestMatcher对象,您可以将其与Spring Security结合使用。

典型的Spring安全配置可能类似于以下示例:

Java
Kotlin
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import static org.springframework.security.config.Customizer.withDefaults; @Configuration(proxyBeanMethods = false) public class MySecurityConfiguration { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.securityMatcher(EndpointRequest.toAnyEndpoint()); http.authorizeHttpRequests((requests) -> requests.anyRequest().hasRole("ENDPOINT_ADMIN")); http.httpBasic(withDefaults()); return http.build(); } } 
            
            

前面的示例使用EndpointRequest.toAnyEndpoint()将请求匹配到任何端点,然后确保所有端点都具有ENDPOINT_ADMIN角色。Endpoint tRequest上还提供了其他几个匹配器方法。详情请参考API文档(HTMLPDF)。

如果您在防火墙后部署应用程序,您可能希望无需身份验证即可访问您的所有执行器端点。您可以通过更改management.endpoints.web.exposure.include属性来执行此操作,如下所示:

Properties
Yaml
management.endpoints.web.exposure.include=*
            
            

此外,如果存在Spring Security,则需要添加自定义安全配置,以允许对端点进行未经身份验证的访问,如下例所示:

Java
Kotlin
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration(proxyBeanMethods = false) public class MySecurityConfiguration { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.securityMatcher(EndpointRequest.toAnyEndpoint()); http.authorizeHttpRequests((requests) -> requests.anyRequest().permitAll()); return http.build(); } } 
            
            
In both of the preceding examples, the configuration applies only to the actuator endpoints. Since Spring Boot’s security configuration backs off completely in the presence of any SecurityFilterChain bean, you need to configure an additional SecurityFilterChain bean with rules that apply to the rest of the application.

2.3.1. Cross Site Request Forgery Protection

由于Spring Boot依赖于Spring Security的默认设置,因此默认情况下打开CSRF保护。这意味着当使用默认安全配置时,需要POST(关机和记录器端点)、PUTDELETE的执行器终结点会收到403(禁止)错误。

We recommend disabling CSRF protection completely only if you are creating a service that is used by non-browser clients.

您可以在Spring Security Reference Guide中找到有关CSRF保护的其他信息。

2.4. Configuring Endpoints

端点自动缓存对不带任何参数的读取操作的响应。要配置端点缓存响应的时间量,请使用其cache.time-to-live属性。下面的示例将Bean终结点缓存的生存时间设置为10秒:

Properties
Yaml
management.endpoint.beans.cache.time-to-live=10s
            
            
The management.endpoint.<name> prefix uniquely identifies the endpoint that is being configured.

2.5. Hypermedia for Actuator Web Endpoints

将添加一个“发现页面”,其中包含指向所有端点的链接。默认情况下,“发现页面”位于/Actuator

要禁用“发现页”,请将以下属性添加到应用程序属性中:

Properties
Yaml
management.endpoints.web.discovery.enabled=false
            
            

当配置了自定义管理上下文路径时,“发现页面”会自动从/Actuator移到管理上下文的根目录。例如,如果管理上下文路径是/Management,则可以从/Management访问发现页面。当管理上下文路径设置为/时,发现页将被禁用,以防止与其他映射冲突的可能性。

2.6. CORS Support

跨域资源共享(CORS)是一个W3C规范,让您可以灵活地指定授权的跨域请求类型。如果您使用的是Spring MVC或Spring WebFlux,则可以配置Actuator的Web端点以支持此类场景。

CORS支持在默认情况下处于禁用状态,只有在设置了management.endpoints.web.cors.allowed-origins属性后才会启用。以下配置允许来自example.com域的GETPOST调用:

Properties
Yaml
management.endpoints.web.cors.allowed-origins=https://example.com
management.endpoints.web.cors.allowed-methods=GET,POST
            
            
See CorsEndpointProperties for a complete list of options.

2.7. Implementing Custom Endpoints

如果添加使用@Endpoint注释的@Bean,则使用@ReadOperation@WriteOperation@DeleteOperation注释的任何方法都会自动通过JMX公开,在Web应用程序中也会通过HTTP公开。通过使用Jersey、Spring MVC或Spring WebFlux,可以通过HTTP公开端点。如果Jersey和Spring MVC都可用,则使用Spring MVC。

下面的示例公开一个返回自定义对象的读取操作:

Java
Kotlin
@ReadOperation
public CustomData getData() {
    return new CustomData("test", 5);
}

            
            

您还可以使用@JmxEndpoint@WebEndpoint编写特定于技术的端点。这些终端受限于其各自的技术。例如,@WebEndpoint仅通过HTTP而不是JMX公开。

您可以使用@EndpointWebExtension@EndpointJmxExtension编写特定于技术的扩展。这些注释允许您提供特定于技术的操作来扩充现有的端点。

最后,如果您需要访问特定于Web框架的功能,您可以实现Servlet或Spring@Controller@RestController端点,但代价是它们在JMX上不可用,或者在使用不同的Web框架时。

2.7.1. Receiving Input

端点上的操作通过它们的参数接收输入。在Web上公开时,这些参数的值取自URL的查询参数和JSON请求正文。当通过JMX公开时,参数被映射到MBean操作的参数。默认情况下,参数是必需的。可以通过使用@javax.注解.Nullable@org.springframework.lang.Nullable.来注释它们,从而使它们成为可选的

您可以将JSON请求正文中的每个根属性映射到端点的参数。考虑以下JSON请求正文:

{
    "name": "test",
    "counter": 42
}
             
             

您可以使用它来调用一个写入操作,该操作接受字符串名称整型计数器参数,如下例所示:

Java
Kotlin
@WriteOperation
public void updateData(String name, int counter) {
    // injects "test" and 42
}

             
             
Because endpoints are technology agnostic, only simple types can be specified in the method signature. In particular, declaring a single parameter with a CustomData type that defines a name and counter properties is not supported.
To let the input be mapped to the operation method’s parameters, Java code that implements an endpoint should be compiled with -parameters, and Kotlin code that implements an endpoint should be compiled with -java-parameters. This will happen automatically if you use Spring Boot’s Gradle plugin or if you use Maven and spring-boot-starter-parent.
Input Type Conversion

如果需要,传递给端点操作方法的参数将自动转换为所需的类型。在调用操作方法之前,通过使用ApplicationConversionService的实例以及任何ConverterGenericConverterBean将通过JMX或HTTP接收的输入转换为所需的类型。

2.7.2. Custom Web Endpoints

@Endpoint@WebEndpoint@EndpointWebExtension上的操作使用Jersey、Spring MVC或Spring WebFlux通过HTTP自动公开。如果Jersey和Spring MVC都可用,则使用Spring MVC。

Web Endpoint Request Predicates

系统会为暴露在Web上的端点上的每个操作自动生成请求谓词。

Path

谓词的路径由端点的ID和暴露在Web上的端点的基本路径确定。缺省的基本路径是/Actuator。例如,ID为SESSIONS的端点使用/Actuator/SESSIONS作为其在谓词中的路径。

您可以通过@Selector注释操作方法的一个或多个参数来进一步定制路径。这样的参数作为路径变量被添加到路径谓词中。调用终结点操作时,变量的值被传递到操作方法中。如果希望捕获所有剩余的路径元素,可以将@Selector(Match=ALL_RELEVING)添加到最后一个参数,并使其成为与字符串[]转换兼容的类型。

HTTP method

谓词的HTTP方法由操作类型决定,如下表所示:

Operation HTTP method

@ReadOperation

获取

@WriteOperation

开机自检

@DeleteOperation

删除

Consumes

对于使用请求主体的<代码>@WriteOperation (HTTP<代码>POST ),谓词的<代码>消耗 子句是application/vnd.spring-boot.actuator.v2+json,应用程序/JSON 。对于所有其他操作,消耗子句为空。

Produces

谓词的Products子句可以由@DeleteOperation@ReadOperation@WriteOperation注释的Products属性确定。该属性是可选的。如果不使用它,Products子句将自动确定。

如果操作方法返回voidvoid,则Products子句为空。如果操作方法返回应用程序,<org.springframework.core.io.Resource,>Products子句是应用程序/八位字节流。对于所有其他操作,Products子句是application/vnd.spring-boot.actuator.v2+json,应用程序/json

Web Endpoint Response Status

端点操作的默认响应状态取决于操作类型(读、写或删除)以及操作返回的内容(如果有的话)。

如果@ReadOperation返回值,则响应状态为200(OK)。如果没有返回值,则响应状态为404(未找到)。

如果@WriteOperation@DeleteOperation返回值,则响应状态为200(OK)。如果不返回值,则响应状态为204(无内容)。

如果在没有必需参数的情况下调用操作,或者调用的参数不能转换为必需类型,则不会调用操作方法,响应状态将为400(Bad Request)。

Web Endpoint Range Requests

您可以使用HTTP范围请求来请求部分HTTP资源。当使用Spring MVC或Spring Web Flux时,返回org.springframework.core.io.Resource的操作自动支持范围请求。

Range requests are not supported when using Jersey.
Web Endpoint Security

Web终结点或特定于Web的终结点扩展上的操作可以将当前的<org.springframework.boot.actuate.endpoint.SecurityContext>java.security.main作为方法参数接收。前者通常与@Nullable结合使用,为经过身份验证和未经身份验证的用户提供不同的行为。后者通常用于使用其isUserInRole(字符串)方法执行授权检查。

2.7.3. Servlet Endpoints

通过实现一个用@ServletEndpoint注释的类,该类还实现Supplier<;EndpointServlet>;,可以将Servlet公开为端点。Servlet端点提供了与Servlet容器的更深层次的集成,但代价是可移植性。它们旨在用于将现有的Servlet公开为端点。对于新端点,应尽可能使用@Endpoint@WebEndpoint注释。

2.7.4. Controller Endpoints

您可以使用@ControllerEndpoint@RestControllerEndpoint来实现仅由Spring MVC或Spring WebFlux公开的端点。方法通过使用Spring MVC和Spring WebFlux的标准注释来映射,例如@Requestmap@Getmap,并将端点的ID用作路径的前缀。控制器端点提供了与Spring Web框架的更深层次的集成,但以可移植性为代价。应尽可能使用@Endpoint@WebEndpoint注释。

2.8. Health Information

您可以使用运行状况信息检查正在运行的应用程序的状态。它经常被监控软件用来在生产系统停机时向某人发出警报。运行状况终结点公开的信息取决于management.endpoint.health.show-detailsmanagement.endpoint.health.show-components属性,可以使用下列值之一进行配置:

Name Description

从不

细节永远不会显示。

何时授权

详细信息仅向授权用户显示。可使用management.endpoint.health.roles.配置授权角色

始终

详细信息将显示给所有用户。

默认值为Never。当用户处于端点的一个或多个角色中时,该用户被视为获得授权。如果终端没有配置角色(默认),则所有经过身份验证的用户都被视为已授权。您可以使用Management.endPot.Health.Roles属性来配置角色。

If you have secured your application and wish to use always, your security configuration must permit access to the health endpoint for both authenticated and unauthenticated users.

健康信息从HealthContributorRegistry(默认情况下,在ApplicationContext中定义的所有实例)的内容中收集。Spring Boot包括许多自动配置的HealthContributor,您也可以编写自己的。

HealthContributor可以是HealthIndicatorCompositeHealthContributorHealthIndicator提供实际健康信息,包括状态CompositeHealthContributor提供其他HealthContributor的组合。综合起来,贡献者形成了一个树形结构来代表整个系统的健康状况。

默认情况下,最终的系统运行状况由StatusAggregator派生,它根据状态的有序列表对每个HealthIndicator中的状态进行排序。排序列表中的第一个状态用作总体健康状态。如果HealthIndicator未返回StatusAggregator已知的状态,则使用未知状态。

You can use the HealthContributorRegistry to register and unregister health indicators at runtime.

2.8.1. Auto-configured HealthIndicators

如果合适,Spring Boot会自动配置下表中列出的HealthIndicator。您也可以通过配置Management.Health.key.Enabled来启用或禁用选定的指标,如下表所示:

Key Name Description

卡桑德拉

CassandraDriverHealthIndicator

检查Cassandra数据库是否已启动。

Couchbase

CouchbaseHealthIndicator

检查Couchbase群集是否已启动。

数据库

DataSourceHealthIndicator

检查是否可以获得到数据源的连接。

磁盘空间

DiskSpaceHealthIndicator

检查磁盘空间是否不足。

ElasticSearch

ElasticsearchRestHealthIndicator

检查Elasticearch群集是否已启动。

Hazelcast

HazelcastHealthIndicator

检查是否启动了Hazelcast服务器。

impxdb

InfluxDbHealthIndicator

检查InfluxDB服务器是否已启动。

jms

JmsHealthIndicator

检查JMS代理是否已启动。

ldap

LdapHealthIndicator

检查是否有一台LDAP服务器处于运行状态。

邮件

MailHealthIndicator

检查邮件服务器是否已启动。

Mongo

MongoHealthIndicator

检查Mongo数据库是否已启动。

ne4j

Neo4jHealthIndicator

检查Neo4j数据库是否已启动。

ping

PingHealthIndicator

始终以up响应。

兔子

RabbitHealthIndicator

检查Rabbit服务器是否已启动。

redis

RedisHealthIndicator

检查Redis服务器是否已启动。

You can disable them all by setting the management.health.defaults.enabled property.

其他HealthIndicator可用,但默认情况下未启用:

Key Name Description

livenessState

LivenessStateHealthIndicator

显示“活动”应用程序的可用性状态。

ReadinessState

ReadinessStateHealthIndicator

显示“就绪性”应用程序可用性状态。

2.8.2. Writing Custom HealthIndicators

要提供定制的健康信息,您可以注册实现HealthIndicator接口的SpringBean。您需要提供Health()方法的实现并返回Health响应。运行状况响应应包括状态,并且可以选择性地包括要显示的其他详细信息。以下代码显示了一个示例HealthIndicator实现:

Java
Kotlin
import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MyHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); if (errorCode != 0) { return Health.down().withDetail("Error Code", errorCode).build(); } return Health.up().build(); } private int check() { // perform some specific health check return ... } } 
             
             
The identifier for a given HealthIndicator is the name of the bean without the HealthIndicator suffix, if it exists. In the preceding example, the health information is available in an entry named my.
Health indicators are usually called over HTTP and need to respond before any connection timeouts. Spring Boot will log a warning message for any health indicator that takes longer than 10 seconds to respond. If you want to configure this threshold, you can use the management.endpoint.health.logging.slow-indicator-threshold property.

除了Spring Boot的预定义状态类型之外,Health还可以返回表示新系统状态的自定义状态。在这种情况下,您还需要提供<代码>StatusAggregator 接口的自定义实现,或者必须使用management.endpoint.health.status.order配置属性配置默认实现。

例如,假设在您的一个HealthIndicator实现中使用了一个新的状态,其代码为致命。要配置严重性顺序,请将以下属性添加到应用程序属性:

Properties
Yaml
management.endpoint.health.status.order=fatal,down,out-of-service,unknown,up
             
             

响应中的HTTP状态代码反映整体运行状况。默认情况下,out_of_servicedown映射到503。任何未映射的运行状况状态,包括up,都映射到200。如果通过HTTP访问健康端点,您可能还希望注册自定义状态映射。配置自定义映射将禁用downout_of_service的默认映射。如果要保留默认映射,则必须与任何自定义映射一起显式配置它们。例如,以下属性将致命映射到503(服务不可用),并保留downout_of_service的默认映射:

Properties
Yaml
management.endpoint.health.status.http-mapping.down=503
management.endpoint.health.status.http-mapping.fatal=503
management.endpoint.health.status.http-mapping.out-of-service=503
             
             
If you need more control, you can define your own HttpCodeStatusMapper bean.

下表显示了内置状态的默认状态映射:

Status Mapping

向下

SERVICE_UNAvailable(503)

服务中断

SERVICE_UNAvailable(503)

向上

默认情况下没有映射,因此HTTP状态为200

未知

默认情况下没有映射,因此HTTP状态为200

2.8.3. Reactive Health Indicators

对于反应式应用程序,比如那些使用Spring WebFlux的应用程序,Reactive HealthContributor为确保应用程序健康提供了一个非阻塞契约。与传统的 ReactiveHealthContributorRegistry>HealthContributor类似,健康信息是从 ReactiveHealthContributorRegistry(默认情况下,您的 ApplicationContext中定义的所有 ReactiveHealthContributor实例)的内容中收集的。不对照反应性API进行检查的常规HealthContributor在弹性调度程序上执行。

In a reactive application, you should use the ReactiveHealthContributorRegistry to register and unregister health indicators at runtime. If you need to register a regular HealthContributor, you should wrap it with ReactiveHealthContributor#adapt.

要从反应式API提供定制的健康信息,您可以注册实现ReactiveHealthIndicator接口的SpringBean。下面的代码显示了一个示例Reactive HealthIndicator实现:

Java
Kotlin
import reactor.core.publisher.Mono; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.ReactiveHealthIndicator; import org.springframework.stereotype.Component; @Component public class MyReactiveHealthIndicator implements ReactiveHealthIndicator { @Override public Mono<Health> health() { return doHealthCheck().onErrorResume((exception) -> Mono.just(new Health.Builder().down(exception).build())); } private Mono<Health> doHealthCheck() { // perform some specific health check return ... } } 
             
             
To handle the error automatically, consider extending from AbstractReactiveHealthIndicator.

2.8.4. Auto-configured ReactiveHealthIndicators

如果合适,Spring Boot会自动配置以下Reactive HealthIndicator

Key Name Description

卡桑德拉

CassandraDriverReactiveHealthIndicator

检查Cassandra数据库是否已启动。

Couchbase

CouchbaseReactiveHealthIndicator

检查Couchbase群集是否已启动。

ElasticSearch

ElasticsearchReactiveHealthIndicator

检查Elasticearch群集是否已启动。

Mongo

MongoReactiveHealthIndicator

检查Mongo数据库是否已启动。

ne4j

Neo4jReactiveHealthIndicator

检查Neo4j数据库是否已启动。

redis

RedisReactiveHealthIndicator

检查Redis服务器是否已启动。

If necessary, reactive indicators replace the regular ones. Also, any HealthIndicator that is not handled explicitly is wrapped automatically.

2.8.5. Health Groups

有时,将健康指标组织成可用于不同目的的组很有用。

若要创建运行状况指示器组,可以使用management.endpoint.health.group.<;name>;属性并指定要包括排除的运行状况指示器ID列表。例如,要创建仅包括数据库指示符的组,您可以定义以下内容:

Properties
Yaml
management.endpoint.health.group.custom.include=db
             
             

然后,您可以通过点击<代码>localhost:8080/actuator/health/custom.查看结果

同样,要创建从组中排除数据库指示符并包括所有其他指示符的组,您可以定义以下内容:

Properties
Yaml
management.endpoint.health.group.custom.exclude=db
             
             

默认情况下,组继承与系统运行状况相同的StatusAggregatorHttpCodeStatusMapper设置。但是,您也可以在每个组的基础上定义这些。如果需要,您还可以覆盖show-DetailsRoles属性:

Properties
Yaml
management.endpoint.health.group.custom.show-details=when-authorized
management.endpoint.health.group.custom.roles=admin
management.endpoint.health.group.custom.status.order=fatal,up
management.endpoint.health.group.custom.status.http-mapping.fatal=500
management.endpoint.health.group.custom.status.http-mapping.out-of-service=500
             
             
You can use @Qualifier("groupname") if you need to register custom StatusAggregator or HttpCodeStatusMapper beans for use with the group.

健康组还可以包括/排除CompositeHealthContributor。您还可以仅包括/排除CompositeHealthContributor的某个组件。这可以使用组件的完全限定名称来完成,如下所示:

management.endpoint.health.group.custom.include="test/primary"
management.endpoint.health.group.custom.exclude="test/primary/b"
             
             

在上面的示例中,自定义组将包括名为HealthContributor,它是复合测试的一个组件。这里,主要本身是一个复合体,名为bHealthContributor将从自定义组中排除。

可以在主端口或管理端口上的附加路径上提供健康组。这在Kubernetes这样的云环境中很有用,在这种环境中,出于安全目的对执行器端点使用单独的管理端口是很常见的。使用单独的端口可能会导致不可靠的运行状况检查,因为即使运行状况检查成功,主应用程序也可能无法正常工作。健康组可以配置其他路径,如下所示:

management.endpoint.health.group.live.additional-path="server:/healthz"
             
             

这将使live健康组在主服务器端口/Health z上可用。前缀是必需的,必须是server:(表示主服务器端口)或management:(表示管理端口,如果已配置)。路径必须是单个路径段。

2.8.6. DataSource Health

DataSource运行状况指示器显示标准数据源和路由数据源Bean的运行状况。路由数据源的运行状况包括其每个目标数据源的运行状况。在健康端点的响应中,使用其路由键来命名路由数据源的每个目标。如果您不希望在指示器的输出中包括路由数据源,请将management.health.db.ignore-routing-data-sources设置为TRUE

2.9. Kubernetes Probes

部署在Kubernetes上的应用程序可以使用容器探测器提供有关其内部状态的信息。根据您的Kubernetes配置,kubelet调用这些探测器并对结果做出反应。

默认情况下,Spring Boot管理您的应用程序可用性状态。如果部署在Kubernetes环境中,Actuator将从ApplicationAvailability接口收集“活动”和“就绪”信息,并在专用的健康指示器LivenessStateHealthIndicatorReadinessStateHealthIndicator中使用该信息。这些指示器显示在全局健康端点上(“/Actuator/Health”)。它们还通过使用健康组“/actuator/Health/livenity”“/Actuator/Health/Ready”公开为单独的HTTP探测器。

然后,您可以使用以下终端信息配置您的Kubernetes基础设施:

livenessProbe:
  httpGet:
    path: "/actuator/health/liveness"
    port: <actuator-port>
  failureThreshold: ...
  periodSeconds: ...

readinessProbe:
  httpGet:
    path: "/actuator/health/readiness"
    port: <actuator-port>
  failureThreshold: ...
  periodSeconds: ...
            
            
<actuator-port> should be set to the port that the actuator endpoints are available on. It could be the main web server port or a separate management port if the "management.server.port" property has been set.

只有当应用程序在Kubernetes环境中运行时,才会自动启用这些健康组。您可以使用management.endpoint.health.probes.enabled配置属性在任何环境中启用它们。

If an application takes longer to start than the configured liveness period, Kubernetes mentions the "startupProbe" as a possible solution. Generally speaking, the "startupProbe" is not necessarily needed here, as the "readinessProbe" fails until all startup tasks are done. This means your application will not receive traffic until it is ready. However, if your application takes a long time to start, consider using a "startupProbe" to make sure that Kubernetes won’t kill your application while it is in the process of starting. See the section that describes how probes behave during the application lifecycle.

如果您的执行器终端部署在单独的管理环境中,则终端不会使用与主应用程序相同的Web基础设施(端口、连接池、框架组件)。在这种情况下,即使主应用程序不能正常工作(例如,它不能接受新连接),探测检查也可能成功。因此,使活动就绪健康组在主服务器端口上可用是个好主意吗?这可以通过设置以下属性来完成:

management.endpoint.health.probes.add-additional-paths=true
            
            

这将使活动在主服务器端口上的/livez就绪处可用。

2.9.1. Checking External State With Kubernetes Probes

执行机构将“活跃度”和“就绪性”探测器配置为健康组。这意味着他们可以使用所有健康组功能。例如,您可以配置其他运行状况指示器:

Properties
Yaml
management.endpoint.health.group.readiness.include=readinessState,customCheck
             
             

默认情况下,Spring Boot不会将其他健康指标添加到这些组中。

“活性”调查不应依赖于外部系统的健康检查。如果应用程序的活动状态被破坏,Kubernetes会尝试通过重启应用程序实例来解决该问题。这意味着,如果外部系统(如数据库、Web API或外部缓存)出现故障,Kubernetes可能会重启所有应用程序实例并创建级联故障。

至于“就绪”探测,检查外部系统的选择必须由应用程序开发人员谨慎做出。因此,Spring Boot在就绪探测中不包括任何额外的运行状况检查。如果应用程序实例的就绪状态为未就绪,则Kubernetes不会将流量路由到该实例。一些外部系统可能不会被应用程序实例共享,在这种情况下,它们可能会被包括在就绪探测中。其他外部系统对应用程序可能不是必需的(应用程序可能有断路器和后备),在这种情况下,它们肯定不应该包括在内。不幸的是,由所有应用程序实例共享的外部系统是常见的,您必须做出判断:将其包括在就绪探测中,并预期当外部服务关闭时应用程序被停止服务,或者将其排除在外,并处理堆栈更高层的故障,可能是通过使用调用方中的断路器。

If all instances of an application are unready, a Kubernetes Service with type=ClusterIP or NodePort does not accept any incoming connections. There is no HTTP error response (503 and so on), since there is no connection. A service with type=LoadBalancer might or might not accept connections, depending on the provider. A service that has an explicit ingress also responds in a way that depends on the implementation — the ingress service itself has to decide how to handle the “connection refused” from downstream. HTTP 503 is quite likely in the case of both load balancer and ingress.

此外,如果应用程序使用Kubernetesautoscaling,它可能会对应用程序从负载均衡器中移除做出不同的反应,这取决于它的autoscaler配置。

2.9.2. Application Lifecycle and Probe States

Kubernetes探测器支持的一个重要方面是它与应用程序生命周期的一致性。AvailablityState(它是应用程序的内存中的内部状态)和实际探测(它公开该状态)之间存在显著差异。根据应用程序生命周期的不同阶段,探测器可能不可用。

Spring Boot在启动和关闭期间发布应用程序事件,探测器可以监听此类事件并公开AvailablityState信息。

下表显示了AvailablityState和不同阶段的HTTP连接器的状态。

当Spring Boot应用程序启动时:

Startup phase LivenessState ReadinessState HTTP server Notes

启动

损坏

拒绝流量

未启动

Kubernetes检查“活性”探测,如果花费的时间太长,则重新启动应用程序。

已开始

正确

拒绝流量

拒绝请求

应用程序上下文被刷新。应用程序执行启动任务,但尚未接收流量。

准备好的

正确

ACCEPTING_TRANSPORT

接受请求

启动任务已完成。应用程序正在接收流量。

当Spring Boot应用程序关闭时:

Shutdown phase Liveness State Readiness State HTTP server Notes

正在运行

正确

ACCEPTING_TRANSPORT

接受请求

已请求关闭。

正常关闭

正确

拒绝流量

新请求被拒绝

如果启用,正常关闭进程将处理正在进行的请求

关闭完成

不适用

不适用

服务器已关闭

关闭应用程序上下文,并关闭应用程序。

See Kubernetes container lifecycle section for more information about Kubernetes deployment.

2.10. Application Information

应用程序信息公开从ApplicationContext中定义的所有InfoContributorBean收集的各种信息。Spring Boot包括许多自动配置的InfoContributorBean,您可以编写自己的Bean。

2.10.1. Auto-configured InfoContributors

在适当的时候,Spring会自动配置以下InfoContributorBean:

ID Name Description Prerequisites

生成

BuildInfoContributor

公开生成信息。

META-INF/Build-info.Properties资源。

环境

EnvironmentInfoContributor

公开Environment中名称以info.开头的所有属性。

没有。

Git

GitInfoContributor

暴露GIT信息。

git.Properties资源。

Java

JavaInfoContributor

显示Java运行时信息。

没有。

操作系统

OsInfoContributor

显示操作系统信息。

没有。

是否启用单个参与者由其management.info.<;id>;.enabled属性控制。不同的参与者对此属性有不同的默认设置,具体取决于他们的先决条件和他们公开的信息的性质。

在没有指示应启用它们的前提条件的情况下,envJavaos贡献者默认处于禁用状态。可以通过将其management.info.<;id>;.enabled属性设置为TRUE来启用每个属性。

默认情况下启用内部版本git信息贡献器。可以通过将其management.info.<;id>;.enabled属性设置为FALSE来禁用它们。或者,要禁用通常在默认情况下启用的每个参与者,请将Management.info.defaults.Enabled属性设置为FALSE

2.10.2. Custom Application Information

启用env贡献器后,您可以通过设置info.*Spring属性来自定义info.*终结点公开的数据。自动显示INFO项下的所有Environment属性。例如,您可以将以下设置添加到应用程序.属性文件中:

Properties
Yaml
info.app.encoding=UTF-8
info.app.java.source=11
info.app.java.target=11
             
             

您也可以在构建时展开信息属性,而不是对这些值进行硬编码。

假设您使用的是Maven,您可以重写前面的示例,如下所示:

Properties
Yaml
info.app.encoding=@project.build.sourceEncoding@
info.app.java.source=@java.version@
info.app.java.target=@java.version@
                  
                  

2.10.3. Git Commit Information

info终结点的另一个有用功能是,它能够在生成项目时发布有关Git源代码存储库状态的信息。如果有GitPropertiesBean可用,则可以使用info终结点来公开这些属性。

A GitProperties bean is auto-configured if a git.properties file is available at the root of the classpath. See "how to generate git information" for more detail.

默认情况下,终结点公开git.Branchgit.Comm.idgit.Comm.time属性(如果存在)。如果您不希望在端点响应中包含这些属性,则需要将它们从git.properties文件中排除。如果要显示完整的Git信息(即git.properties的完整内容),请使用madement.info.git.mode属性,如下所示:

Properties
Yaml
management.info.git.mode=full
             
             

若要完全禁用来自info终结点的GIT提交信息,请将Management.info.git.Enabled属性设置为FALSE,如下所示:

Properties
Yaml
management.info.git.enabled=false
             
             

2.10.4. Build Information

如果BuildPropertiesBean可用,info终结点还可以发布有关您的构建的信息。如果类路径中有META-INF/Build-info.Properties文件,就会发生这种情况。

The Maven and Gradle plugins can both generate that file. See "how to generate build information" for more details.

2.10.5. Java Information

info终结点发布有关Java运行时环境的信息,有关更多详细信息,请参阅Java Info

2.10.6. OS Information

INFO终结点发布有关您的操作系统的信息,有关详细信息,请参阅OsInfo

2.10.7. Writing Custom InfoContributors

要提供定制应用程序信息,您可以注册实现InfoContributor接口的SpringBean。

下面的示例提供了一个具有单个值的示例条目:

Java
Kotlin
import java.util.Collections; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class MyInfoContributor implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail("example", Collections.singletonMap("key", "value")); } } 
             
             

如果您到达INFO终结点,您应该会看到包含以下附加条目的响应:

{
    "example": {
        "key" : "value"
    }
}
             
             

3. Monitoring and Management Over HTTP

如果您正在开发Web应用程序,Spring Boot Actuator会自动将所有启用的端点配置为通过HTTP公开。默认约定是使用终结点的id作为URL路径,其前缀为/Actuator。例如,Health被公开为/Actuator/Health

Actuator is supported natively with Spring MVC, Spring WebFlux, and Jersey. If both Jersey and Spring MVC are available, Spring MVC is used.
Jackson is a required dependency in order to get the correct JSON responses as documented in the API documentation (HTML or PDF).

3.1. Customizing the Management Endpoint Paths

有时,自定义管理端点的前缀很有用。例如,您的应用程序可能已经将/Actuator用于其他目的。您可以使用management.endpoints.web.base-path属性更改管理端点的前缀,如下例所示:

Properties
Yaml
management.endpoints.web.base-path=/manage
            
            

前面的Applation.Properties示例将端点从/Actuator/{id}更改为/Manage/{id}(例如,/Manage/Info)。

Unless the management port has been configured to expose endpoints by using a different HTTP port, management.endpoints.web.base-path is relative to server.servlet.context-path (for servlet web applications) or spring.webflux.base-path (for reactive web applications). If management.server.port is configured, management.endpoints.web.base-path is relative to management.server.base-path.

如果要将终结点映射到其他路径,可以使用management.endpoints.web.path-mapping属性。

下面的示例将/Actuator/Health重新映射到/Health check

Properties
Yaml
management.endpoints.web.base-path=/
management.endpoints.web.path-mapping.health=healthcheck
            
            

3.2. Customizing the Management Server Port

对于基于云的部署,通过使用默认的HTTP端口公开管理终端是明智的选择。但是,如果您的应用程序在您自己的数据中心内运行,您可能更喜欢使用不同的HTTP端口来公开终结点。

您可以设置madement.server.port属性来更改HTTP端口,如下例所示:

Properties
Yaml
management.server.port=8081
            
            
On Cloud Foundry, by default, applications receive requests only on port 8080 for both HTTP and TCP routing. If you want to use a custom management port on Cloud Foundry, you need to explicitly set up the application’s routes to forward traffic to the custom port.

3.3. Configuring Management-specific SSL

当配置为使用自定义端口时,您还可以使用各种Management.server.ssl.*属性为管理服务器配置其自己的SSL。例如,这样做允许管理服务器通过HTTP可用,而主应用程序使用HTTPS,如以下属性设置所示:

Properties
Yaml
server.port=8443
server.ssl.enabled=true
server.ssl.key-store=classpath:store.jks
server.ssl.key-password=secret
management.server.port=8080
management.server.ssl.enabled=false
            
            

或者,主服务器和管理服务器都可以使用SSL,但具有不同的密钥存储,如下所示:

Properties
Yaml
server.port=8443
server.ssl.enabled=true
server.ssl.key-store=classpath:main.jks
server.ssl.key-password=secret
management.server.port=8080
management.server.ssl.enabled=true
management.server.ssl.key-store=classpath:management.jks
management.server.ssl.key-password=secret
            
            

3.4. Customizing the Management Server Address

您可以通过设置Management.server.Address属性来自定义管理终结点可用的地址。如果您只想在内部或面向操作的网络上侦听,或者只想侦听来自本地主机的连接,那么这样做很有用。

You can listen on a different address only when the port differs from the main server port.

以下示例Applation.Properties不允许远程管理连接:

Properties
Yaml
management.server.port=8081
management.server.address=127.0.0.1
            
            

3.5. Disabling HTTP Endpoints

如果您不想通过HTTP公开终端,可以将管理端口设置为-1,如下例所示:

Properties
Yaml
management.server.port=-1
            
            

您也可以使用management.endpoints.web.exposure.exclude属性来实现此目的,如下面的示例所示:

Properties
Yaml
management.endpoints.web.exposure.exclude=*
            
            

4. Monitoring and Management over JMX

Java管理扩展(JMX)提供了监视和管理应用程序的标准机制。默认情况下,此功能未启用。您可以通过将spring.jmx.Enabled配置属性设置为true来启用它。Spring Boot将最合适的MBeanServer公开为ID为mbeanServer的Bean。您的任何使用Spring JMX注释(@ManagedResource@ManagedAttribute@ManagedOperation)批注的Bean都向它公开。

如果您的平台提供了标准的MBeanServer,如果需要,Spring Boot将使用它并缺省为VMMBeanServer。如果所有操作都失败,则创建一个新的MBeanServer

有关更多详细信息,请参阅JmxAutoConfiguration类。

默认情况下,Spring Boot还将管理端点公开为org.springFrawork.boot域下的JMX MBean。要完全控制JMX域中的端点注册,请考虑注册您自己的EndpointObjectNameFactory实现。

4.1. Customizing MBean Names

MBean的名称通常由终结点的id生成。例如,Health终结点公开为org.springFrawork.ot:type=Endpoint,name=Health

如果您的应用程序包含多个SpringApplicationContext,您可能会发现名称冲突。要解决此问题,可以将spring.jmx.only-name属性设置为true,以便MBean名称始终是唯一的。

您还可以自定义在其下公开端点的JMX域。以下设置显示了在Application.Properties中执行此操作的示例:

Properties
Yaml
spring.jmx.unique-names=true
management.endpoints.jmx.domain=com.example.myapp
            
            

4.2. Disabling JMX Endpoints

如果不想通过JMX公开端点,可以将management.endpoints.jmx.exposure.exclude属性设置为<代码>* ,如下面的示例所示:

Properties
Yaml
management.endpoints.jmx.exposure.exclude=*
            
            

5. Observability

可观测性是从外部观察运行系统的内部状态的能力。它由伐木、度量和痕迹三大支柱组成。

对于度量和跟踪,Spring Boot使用微米观测。要创建您自己的观察(这将导致度量和跟踪),您可以注入一个ObservationRegistry

import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import org.springframework.stereotype.Component; @Component public class MyCustomObservation { private final ObservationRegistry observationRegistry; public MyCustomObservation(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } public void doSomething() { Observation.createNotStarted("doSomething", this.observationRegistry) .lowCardinalityKeyValue("locale", "en-US") .highCardinalityKeyValue("userId", "42") .observe(() -> { // Execute business logic here }); } } 
           
           
Low cardinality tags will be added to metrics and traces, while high cardinality tags will only be added to traces.

ObservationPredicateGlobalObservationConferenceObservationHandler类型的Bean将在ObservationRegistry上自动注册。您还可以注册任意数量的ObservationRegistryCustomizerBean以进一步配置注册表。

有关更多详细信息,请参阅微米观测文档

Observability for JDBC and R2DBC can be configured using separate projects. For JDBC, the Datasource Micrometer project provides a Spring Boot starter which automatically creates observations when JDBC operations are invoked. Read more about it in the reference documentation. For R2DBC, the Spring Boot Auto Configuration for R2DBC Observation creates observations for R2DBC query invocations.

接下来的部分将提供有关日志记录、指标和跟踪的更多详细信息。

6. Loggers

Spring Boot Actuator包括在运行时查看和配置应用程序的日志级别的能力。您可以查看整个列表,也可以查看单个记录器的配置,该配置由显式配置的日志记录级别以及日志记录框架为其提供的有效日志记录级别组成。这些级别可以是以下级别之一:

  • 跟踪

  • 调试

  • 信息

  • 警告

  • 错误

  • 致命

  • 关闭

NULL表示没有显式配置。

6.1. Configure a Logger

要配置给定的记录器,将一个部分实体POST到资源的URI,如下例所示:

{
    "configuredLevel": "DEBUG"
}
            
            
To “reset” the specific level of the logger (and use the default configuration instead), you can pass a value of null as the configuredLevel.

7. Metrics

Spring Boot Actuator为微米提供依赖项管理和自动配置,这是一个支持多种监控系统的应用程序指标外观,包括:

To learn more about Micrometer’s capabilities, see its reference documentation, in particular the concepts section.

7.1. Getting started

Spring Boot自动配置一个复合MeterRegistry,并为它在类路径上找到的每个受支持的实现向该复合中添加一个注册表。在您的运行时类路径中具有microeter-home-{system}的依赖关系,就足以让Spring Boot配置注册表。

大多数注册表都有共同的特征。例如,即使微米注册表实现位于类路径上,也可以禁用特定注册表。以下示例禁用Datadog:

Properties
Yaml
management.datadog.metrics.export.enabled=false
            
            

您还可以禁用所有注册表,除非注册表特定的属性另有说明,如下例所示:

Properties
Yaml
management.defaults.metrics.export.enabled=false
            
            

Spring Boot还将任何自动配置的注册表添加到Metrics类上的全局静态复合注册表中,除非您明确告诉它不要这样做:

Properties
Yaml
management.metrics.use-global-registry=false
            
            

在向注册表注册任何仪表之前,您可以注册任意数量的MeterRegistryCustomizerBean以进一步配置注册表,例如应用通用标签:

Java
Kotlin
import io.micrometer.core.instrument.MeterRegistry; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyMeterRegistryConfiguration { @Bean public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() { return (registry) -> registry.config().commonTags("region", "us-east-1"); } } 
            
            

通过更具体地说明泛型类型,您可以将定制应用于特定的注册表实现:

Java
Kotlin
import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.config.NamingConvention; import io.micrometer.graphite.GraphiteMeterRegistry; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyMeterRegistryConfiguration { @Bean public MeterRegistryCustomizer<GraphiteMeterRegistry> graphiteMetricsNamingConvention() { return (registry) -> registry.config().namingConvention(this::name); } private String name(String name, Meter.Type type, String baseUnit) { return ... } } 
            
            

7.2. Supported Monitoring Systems

本节简要介绍了每个受支持的监控系统。

7.2.1. AppOptics

默认情况下,AppOptics注册中心定期将指标推送到api.appoptics.com/v1/measurements.要将指标导出到SaaSAppOptics,必须提供您的API令牌:

Properties
Yaml
management.appoptics.metrics.export.api-token=YOUR_TOKEN
             
             

7.2.2. Atlas

默认情况下,指标将导出到本地计算机上运行的Atlas。您可以提供Atlas服务器的位置:

Properties
Yaml
management.atlas.metrics.export.uri=https://atlas.example.com:7101/api/v1/publish
             
             

7.2.3. Datadog

Datadog注册中心定期将指标推送到datadoghq。要将指标导出到Datadog,您必须提供您的API密钥:

Properties
Yaml
management.datadog.metrics.export.api-key=YOUR_KEY
             
             

如果另外提供应用程序密钥(可选),则还将导出仪表描述、类型和基本单位等元数据:

Properties
Yaml
management.datadog.metrics.export.api-key=YOUR_API_KEY
management.datadog.metrics.export.application-key=YOUR_APPLICATION_KEY
             
             

默认情况下,指标被发送到Datadog US站点(api.datadoghq.com)。如果您的Datadog项目托管在其他站点之一上,或者您需要通过代理发送指标,请相应地配置URI:

Properties
Yaml
management.datadog.metrics.export.uri=https://api.datadoghq.eu
             
             

您还可以更改将指标发送到Datadog的间隔:

Properties
Yaml
management.datadog.metrics.export.step=30s
             
             

7.2.4. Dynatrace

Dynatrace提供了两个指标摄取API,这两个API都是针对微米实现的。您可以在此处找到关于微米指标摄取的Dynatrace文档。v1命名空间中的配置属性仅在导出到Timeseries v1 API时适用。v2命名空间中的配置属性仅在导出到Metrics v2 API时适用。请注意,此集成一次只能导出到API的v1v2版本,首选v2。如果在v1命名空间中设置了Device-id(v1需要,但在v2中未使用),则指标将导出到v1终结点。否则,假定为v2

v2 API

您可以通过两种方式使用v2 API。

Auto-configuration

Dynatrace自动配置可用于由OneAgent或Kubernetes的Dynatrace操作员监控的主机。

本地OneAgent:如果主机上正在运行OneAgent,则指标会自动导出到本地OneAgent摄取终结点。摄取端点将指标转发到Dynatrace后端。

Dynatrace Kubernetes运算符:在安装了Dynatrace运算符的Kubernetes中运行时,注册表将自动从运算符获取您的端点URI和API令牌。

这是默认行为,除了对io.micrometer:micrometer-registry-dynatrace.的依赖外,不需要特殊设置

Manual configuration

如果没有自动配置,则需要Metrics v2 API的端点和API令牌。API令牌必须具有“摄取指标”(metrics.ingest)权限集。我们建议将令牌的范围限制为此权限。您必须确保端点URI包含路径(例如,/api/v2/metrics/ingest):

根据您的部署选项,Metrics API v2接收端点的URL会有所不同:

  • 软件即服务:https://{your-environment-id}.live.dynatrace.com/api/v2/metrics/ingest

  • 托管部署:https://{your-domain}/e/{your-environment-id}/api/v2/metrics/ingest

以下示例使用示例环境ID配置指标导出:

Properties
Yaml
management.dynatrace.metrics.export.uri=https://example.live.dynatrace.com/api/v2/metrics/ingest
management.dynatrace.metrics.export.api-token=YOUR_TOKEN
               
               

在使用Dynatrace v2 API时,可以使用以下可选功能(更多详细信息请参阅Dynatrace文档):

  • 指标键前缀:设置附加到所有导出的指标键的前缀。

  • 使用Dynatrace元数据丰富:如果OneAgent或Dynatrace操作符正在运行,则使用其他元数据(例如,关于主机、进程或Pod)来丰富指标。

  • 默认维:指定添加到所有导出的度量的键-值对。如果使用微米指定具有相同关键字的标记,则它们将覆盖默认尺寸。

  • 使用Dynatrace汇总仪器:在某些情况下,微米Dynatrace注册创建的指标被拒绝。在Microeter 1.9.x中,通过引入DyNatrace特定的摘要仪器修复了这一问题。将此切换设置为FALSE将强制Microeter回退到1.9.x之前的默认行为。只有在从千分尺1.8.x迁移到1.9.x时遇到问题时才能使用。

可以不指定URI和API令牌,如下例所示。在此方案中,将使用自动配置的端点:

Properties
Yaml
management.dynatrace.metrics.export.v2.metric-key-prefix=your.key.prefix
management.dynatrace.metrics.export.v2.enrich-with-dynatrace-metadata=true
management.dynatrace.metrics.export.v2.default-dimensions.key1=value1
management.dynatrace.metrics.export.v2.default-dimensions.key2=value2
management.dynatrace.metrics.export.v2.use-dynatrace-summary-instruments=true
               
               
v1 API (Legacy)

Dynatrace v1 API指标注册中心通过使用Timeseries v1 API定期将指标推送到配置的URI。为了向后兼容现有设置,当设置了Device-id时(v1需要,但在v2中不使用),指标将被导出到TimeSeriesv1端点。要将指标导出到Dynatrace,必须提供您的API令牌、设备ID和URI:

Properties
Yaml
management.dynatrace.metrics.export.uri=https://{your-environment-id}.live.dynatrace.com
management.dynatrace.metrics.export.api-token=YOUR_TOKEN
management.dynatrace.metrics.export.v1.device-id=YOUR_DEVICE_ID
              
              

对于v1 API,您必须指定不带路径的基本环境URI,因为v1端点路径是自动添加的。

Version-independent Settings

除了API端点和令牌之外,您还可以更改向Dynatrace发送指标的间隔。默认导出间隔为60s。以下示例将导出间隔设置为30秒:

Properties
Yaml
management.dynatrace.metrics.export.step=30s
              
              

您可以在测微计文档Dynatrace文档中找到有关如何设置微米的Dynatrace导出器的详细信息。

7.2.5. Elastic

默认情况下,指标会导出到您的本地计算机上运行的Elastic。您可以使用以下属性提供要使用的弹性服务器的位置:

Properties
Yaml
management.elastic.metrics.export.host=https://elastic.example.com:8086
             
             

7.2.6. Ganglia

默认情况下,指标被导出到您的本地计算机上运行的Ganglia。您可以提供Ganglia服务器主机和端口,如下例所示:

Properties
Yaml
management.ganglia.metrics.export.host=ganglia.example.com
management.ganglia.metrics.export.port=9649
             
             

7.2.7. Graphite

默认情况下,指标将导出到本地计算机上运行的Graphite。您可以提供Graphite服务器主机和端口,如下例所示:

Properties
Yaml
management.graphite.metrics.export.host=graphite.example.com
management.graphite.metrics.export.port=9004
             
             

Microeter提供了一个默认的HierarchicalNameMapper,它控制如何将维度仪表ID映射到平面分层名称

要控制此行为,请定义您的GraphiteMeterRegistry并提供您自己的HierarchicalNameMapper。除非您定义自己的Bean,否则会提供自动配置的GraphiteConfig时钟Bean:

Java
Kotlin
import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.config.NamingConvention; import io.micrometer.core.instrument.util.HierarchicalNameMapper; import io.micrometer.graphite.GraphiteConfig; import io.micrometer.graphite.GraphiteMeterRegistry; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyGraphiteConfiguration { @Bean public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) { return new GraphiteMeterRegistry(config, clock, this::toHierarchicalName); } private String toHierarchicalName(Meter.Id id, NamingConvention convention) { return ... } } 
                  
                  

7.2.8. Humio

默认情况下,Humio注册中心定期将指标推送到Cloud.humio.com。要将指标导出到SaaSHumio,您必须提供您的API令牌:

Properties
Yaml
management.humio.metrics.export.api-token=YOUR_TOKEN
             
             

您还应该配置一个或多个标记,以标识要将指标推送到的数据源:

Properties
Yaml
management.humio.metrics.export.tags.alpha=a
management.humio.metrics.export.tags.bravo=b
             
             

7.2.9. Influx

默认情况下,指标将以默认配置导出到您的本地计算机上运行的inumxv1实例。要将指标导出到InfluxDB v2,需要配置org存储桶和用于编写指标的身份验证令牌。您可以使用以下命令提供要使用的流入服务器的位置:

Properties
Yaml
management.influx.metrics.export.uri=https://influx.example.com:8086
             
             

7.2.10. JMX

Microeter提供了到JMX的分层映射,主要是作为一种廉价且可移植的本地指标查看方式。默认情况下,指标导出到指标JMX域。您可以使用以下方式提供要使用的域:

Properties
Yaml
management.jmx.metrics.export.domain=com.example.app.metrics
             
             

Microeter提供了一个默认的HierarchicalNameMapper,它控制如何将维度仪表ID映射到平面分层名称

要控制此行为,请定义您的JmxMeterRegistry并提供您自己的HierarchicalNameMapper。除非您定义自己的Bean,否则会提供自动配置的JmxConfig时钟Bean:

Java
Kotlin
import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.config.NamingConvention; import io.micrometer.core.instrument.util.HierarchicalNameMapper; import io.micrometer.jmx.JmxConfig; import io.micrometer.jmx.JmxMeterRegistry; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyJmxConfiguration { @Bean public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) { return new JmxMeterRegistry(config, clock, this::toHierarchicalName); } private String toHierarchicalName(Meter.Id id, NamingConvention convention) { return ... } } 
                  
                  

7.2.11. KairosDB

默认情况下,指标会导出到您的本地计算机上运行的KairosDB。您可以使用以下命令提供要使用的KairosDB服务器的位置:

Properties
Yaml
management.kairos.metrics.export.uri=https://kairosdb.example.com:8080/api/v1/datapoints
             
             

7.2.12. New Relic

New Relic注册中心定期将指标推送到New Relic。要将指标导出到New Relic,您必须提供您的API密钥和帐户ID:

Properties
Yaml
management.newrelic.metrics.export.api-key=YOUR_KEY
management.newrelic.metrics.export.account-id=YOUR_ACCOUNT_ID
             
             

您还可以更改将度量发送到New Relic的间隔:

Properties
Yaml
management.newrelic.metrics.export.step=30s
             
             

默认情况下,指标通过REST调用发布,但如果类路径上有Java代理API,您也可以使用它:

Properties
Yaml
management.newrelic.metrics.export.client-provider-type=insights-agent
             
             

最后,您可以通过定义自己的NewRelicClientProviderBean来实现完全控制。

7.2.13. OpenTelemetry

默认情况下,指标会导出到您的本地计算机上运行的OpenTelemeter。您可以使用以下命令提供要使用的OpenTelemtry指标终结点的位置:

Properties
Yaml
management.otlp.metrics.export.url=https://otlp.example.com:4318/v1/metrics
             
             

7.2.14. Prometheus

Prometheus希望抓取或轮询单个应用程序实例的指标。Spring Boot在/Actuator/Prometheus处提供了一个执行器终结点,以便以适当的格式显示Prometheus sccrp。

By default, the endpoint is not available and must be exposed. See exposing endpoints for more details.

以下示例添加到prometheus.yml中:

scrape_configs:
  - job_name: "spring"
    metrics_path: "/actuator/prometheus"
    static_configs:
      - targets: ["HOST:PORT"]
             
             

还支持普罗米修斯样本。若要启用此功能,应存在span ConextSupplierBean。如果您使用微米跟踪,这将自动为您配置,但如果您愿意,您始终可以创建自己的。请查看Prometheus Docs,因为此功能需要在Prometheus端明确启用,并且仅使用OpenMetrics格式支持。

对于可能存在的时间不够长而无法抓取的临时或批处理作业,您可以使用Prometheus Pushateway支持向Prometheus公开指标。要启用普罗米修斯推送网关支持,请向您的项目添加以下依赖项:

<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_pushgateway</artifactId>
</dependency>
             
             

当类路径上存在Prometheus PushGateway依赖项并且management.prometheus.metrics.export.pushgateway.enabled属性设置为True时,将自动配置一个PrometheusPushGatewayManagerBean。它管理将指标推送到普罗米修斯推送网关。

您可以使用management.prometheus.metrics.export.pushgateway.下的属性来优化PrometheusPushGatewayManager对于高级配置,您还可以提供您自己的PrometheusPushGatewayManagerBean。

7.2.15. SignalFx

SignalFx注册中心定期将指标推送到SignalFx。要将指标导出到SignalFx,您必须提供访问令牌:

Properties
Yaml
management.signalfx.metrics.export.access-token=YOUR_ACCESS_TOKEN
             
             

您还可以更改将指标发送到SignalFx的间隔:

Properties
Yaml
management.signalfx.metrics.export.step=30s
             
             

7.2.16. Simple

Microeter附带一个简单的内存后端,如果没有配置其他注册表,该后端会自动用作后备。这使您可以看到在指标端点中收集了哪些指标。

一旦您使用任何其他可用的后端,内存中的后端就会自动禁用。您也可以显式禁用它:

Properties
Yaml
management.simple.metrics.export.enabled=false
             
             

7.2.17. Stackdriver

StackDRIVER注册表会定期将指标推送到StackDRIVER。要将指标导出到SaaSStackDrive,您必须提供您的Google Cloud项目ID:

Properties
Yaml
management.stackdriver.metrics.export.project-id=my-project
             
             

您还可以更改将指标发送到StackDRIVER的间隔:

Properties
Yaml
management.stackdriver.metrics.export.step=30s
             
             

7.2.18. StatsD

StatsD注册中心急切地通过UDP将指标推送到StatsD代理。默认情况下,指标将导出到本地计算机上运行的StatsD代理。您可以使用以下命令提供要使用的StatsD代理主机、端口和协议:

Properties
Yaml
management.statsd.metrics.export.host=statsd.example.com
management.statsd.metrics.export.port=9125
management.statsd.metrics.export.protocol=udp
             
             

您还可以更改要使用的StatsD线路协议(默认为Datadog):

Properties
Yaml
management.statsd.metrics.export.flavor=etsy
             
             

7.2.19. Wavefront

Wavefront注册表定期将度量推送到Wavefront。如果要将指标直接导出到Wavefront,则必须提供您的API令牌:

Properties
Yaml
management.wavefront.api-token=YOUR_API_TOKEN
             
             

或者,您可以在您的环境中使用Wavefront SideCar或内部代理将指标数据转发到Wavefront API主机:

Properties
Yaml
management.wavefront.uri=proxy://localhost:2878
             
             
If you publish metrics to a Wavefront proxy (as described in the Wavefront documentation), the host must be in the proxy://HOST:PORT format.

您还可以更改将指标发送到Wavefront的间隔:

Properties
Yaml
management.wavefront.metrics.export.step=30s
             
             

7.3. Supported Metrics and Meters

Spring Boot为多种技术提供自动仪表注册。在大多数情况下,默认设置提供了可发布到任何受支持的监控系统的合理指标。

7.3.1. JVM Metrics

自动配置通过使用核心微米类启用JVM指标。JVM指标以JVM.计量器名称发布。

提供了以下JVM指标:

  • 各种内存和缓冲池详细信息

  • 与垃圾收集相关的统计信息

  • 线程利用率

  • 已加载和已卸载的类数

  • JVM版本信息

  • JIT编译时间

7.3.2. System Metrics

自动配置通过使用核心微米类启用系统指标。系统指标发布在系统.进程.磁盘.计量器名称下。

提供了以下系统指标:

  • CPU指标

  • 文件描述符度量

  • 正常运行时间指标(应用程序一直在运行的时间量和绝对启动时间的固定指标)

  • 可用的磁盘空间

7.3.3. Application Startup Metrics

自动配置公开了应用程序启动时间指标:

  • Applation.started.time:启动应用程序所用的时间。

  • Application.Ready.time:应用程序准备好处理请求所需的时间。

指标由应用程序类的完全限定名称标记。

7.3.4. Logger Metrics

自动配置启用Logback和Log4J2的事件指标。详细信息发布在log4j2.Events.logback.Events.计量器名称下。

7.3.5. Task Execution and Scheduling Metrics

自动配置允许检测所有可用的ThreadPoolTaskExecutorThreadPoolTaskSchedulerBean,只要下面的ThreadPoolExecutor可用。指标由Executor的名称标记,该名称派生自Bean名称。

7.3.6. Spring MVC Metrics

自动配置支持对由Spring MVC控制器和功能处理程序处理的所有请求进行检测。默认情况下,生成的指标名称为HTTP.server.Requests。您可以通过设置management.observations.http.server.requests.name属性来自定义名称。

默认情况下,Spring MVC相关指标使用以下信息进行标记:

Tag Description

异常

处理请求时引发的任何异常的简单类名。

方法

请求的方法(例如,GETPOST)

结果

请求的结果,基于响应的状态代码。1xx是信息性,2xx是成功,3xx是重定向,4xx是客户端错误,5xx是SERVER_ERROR

状态

响应的HTTP状态代码(例如,200500)

URI

变量替换之前的请求URI模板(如果可能)(例如,/api/Person/{id})

要添加默认标记,需要提供一个@Bean,它从DefaultServerRequestObservationConvention包扩展org.springframework.http.observation。要替换默认标记,请提供实现ServerRequestObservationConvention.的<代码>@Bean

In some cases, exceptions handled in web controllers are not recorded as request metrics tags. Applications can opt in and record exceptions by setting handled exceptions as request attributes.

默认情况下,所有请求都会得到处理。要定制过滤器,请提供实现FilterRegistrationBean<;WebMvcMetricsFilter>;.的<代码>@Bean

7.3.7. Spring WebFlux Metrics

自动配置支持对由Spring WebFlux控制器和功能处理程序处理的所有请求进行检测。默认情况下,生成的指标名称为HTTP.server.Requests。您可以通过设置management.observations.http.server.requests.name属性来自定义名称。

默认情况下,WebFlux相关指标使用以下信息进行标记:

Tag Description

异常

处理请求时引发的任何异常的简单类名。

方法

请求的方法(例如,GETPOST)

结果

请求的结果,基于响应的状态代码。1xx是信息性,2xx是成功,3xx是重定向,4xx是客户端错误,5xx是SERVER_ERROR

状态

响应的HTTP状态代码(例如,200500)

URI

变量替换之前的请求URI模板(如果可能)(例如,/api/Person/{id})

要添加默认标记,需要提供一个@Bean,它从DefaultServerRequestObservationConvention包扩展org.springframework.http.observation.reactive。要替换默认标记,请提供实现ServerRequestObservationConvention.的<代码>@Bean

In some cases, exceptions handled in controllers and handler functions are not recorded as request metrics tags. Applications can opt in and record exceptions by setting handled exceptions as request attributes.

7.3.8. Jersey Server Metrics

自动配置支持对Jersey JAX-RS实现处理的所有请求进行检测。默认情况下,生成的指标名称为HTTP.server.Requests。您可以通过设置management.observations.http.server.requests.name属性来自定义名称。

默认情况下,Jersey服务器指标使用以下信息进行标记:

Tag Description

异常

处理请求时引发的任何异常的简单类名。

方法

请求的方法(例如,GETPOST)

结果

请求的结果,基于响应的状态代码。1xx是信息性,2xx是成功,3xx是重定向,4xx是客户端错误,5xx是SERVER_ERROR

状态

响应的HTTP状态代码(例如,200500)

URI

变量替换之前的请求URI模板(如果可能)(例如,/api/Person/{id})

要定制标记,请提供实现JerseyTagsProvider@Bean

7.3.9. HTTP Client Metrics

Spring Boot Actuator管理RestTemplateWebClient的检测。为此,您必须注入自动配置的构建器并使用它来创建实例:

  • RestTemplateBuilderforRestTemplateBuilder

  • WebClient.Builder用于WebClient

您还可以手动应用负责此检测的定制器,即ObservationRestTemplateCustomizerObservationWebClientCustomizer

默认情况下,生成的指标名为HTTP.CLIENT.REQUESTS。您可以通过设置management.observations.http.client.requests.name属性来自定义名称。

默认情况下,由插入指令的客户端生成的指标使用以下信息进行标记:

Tag Description

客户端名称

URI的主机部分

方法

请求的方法(例如,GETPOST)

结果

请求的结果,基于响应的状态代码。1xx是信息性,2xx是成功,3xx是重定向,4xx是CLIENT_ERROR,5xx是SERVER_ERROR。否则为未知

状态

响应的HTTP状态代码(如果可用)(例如,200500)或IO_ERROR,用于I/O问题。否则为CLIENT_ERROR

URI

变量替换之前的请求URI模板(如果可能)(例如,/api/Person/{id})

要在使用ClientRequestObservationConvention模板时自定义标记,请提供一个@Bean,它从org.springframework.http.client.observation包实现RESTTEMPLATE。要在使用WebClient时定制标记,请提供一个从ClientRequestObservationConvention包实现org.springframework.web.reactive.function.client@Bean

7.3.10. Tomcat Metrics

仅当启用了MBeanRegistry时,自动配置才会启用Tomcat的检测。默认情况下,MBean注册表是禁用的,但您可以通过将server.tomcat.mbeanregistry.enabled设置为TRUE来启用它。

Tomcat指标以tomcat.指标名称发布。

7.3.11. Cache Metrics

自动配置允许在启动时插入所有可用的缓存实例,指标以缓存为前缀。缓存插装针对一组基本指标进行了标准化。此外,还可以使用特定于缓存的其他指标。

支持以下缓存库:

  • 缓存2k

  • 咖啡因

  • 黑兹卡斯特

  • 任何符合JCache(JSR-107)的实施

  • 雷迪斯人

指标由缓存的名称和从Bean名称派生的CacheManager的名称来标记。

Only caches that are configured on startup are bound to the registry. For caches not defined in the cache’s configuration, such as caches created on the fly or programmatically after the startup phase, an explicit registration is required. A CacheMetricsRegistrar bean is made available to make that process easier.

7.3.12. Spring GraphQL Metrics

自动配置允许检测任何支持的传输的GraphQL查询。

Spring Boot使用以下命令记录graph ql.Request计时器:

Tag Description Sample values

结果

请求结果

“成功”、“错误”

一个GraphQL查询可能涉及许多DataFetcher调用,因此有一个专用的graph ql.datafetcher计时器:

Tag Description Sample values

路径

数据抓取器路径

“Query.project”

结果

数据获取结果

“成功”、“错误”

分布摘要统计非琐碎事件的数量此指标对于检测“N+1”数据获取问题和考虑批量加载非常有用;它提供数据获取程序调用的“总数”<代码>可用于<;<;application-properties#application-properties.actuator.management.metrics.distribution.maximum-expected-value,配置的更多选项

单个响应可以包含许多GraphQL错误,由Graphql.Error计数器计数:

Tag Description Sample values

错误类型

错误类型

“DataFetchingException”

错误路径

错误的JSON路径

“$.project”

7.3.13. DataSource Metrics

自动配置支持对所有可用的DataSource对象进行检测,这些对象的度量以jDBC.Connections为前缀。数据源检测会产生表示池中当前活动、空闲、最大允许连接和最小允许连接的量规。

指标还通过根据Bean名称计算的DataSource的名称进行标记。

By default, Spring Boot provides metadata for all supported data sources. You can add additional DataSourcePoolMetadataProvider beans if your favorite data source is not supported. See DataSourcePoolMetadataProvidersConfiguration for examples.

此外,特定于Hikari的指标使用hikaricp前缀公开。每个指标都由池的名称来标记(您可以使用spring.datource.name来控制它)。

7.3.14. Hibernate Metrics

如果org.hibernate.orm:hibernate-micrometer位于类路径上,则启用了统计信息的所有可用的HibernateEntityManager实例都将使用名为Hibernate的指标进行检测。

指标还通过从Bean名称派生的EntityManagerFactory的名称进行标记。

要启用统计信息,必须将标准JPA属性hibernate.GENERATE_STATISTICS设置为true。您可以在自动配置的EntityManagerFactory上启用:

Properties
Yaml
spring.jpa.properties[hibernate.generate_statistics]=true
             
             

7.3.15. Spring Data Repository Metrics

自动配置支持对所有Spring数据存储库方法调用进行检测。默认情况下,生成的指标名称为spring.data.repository.invocations.您可以通过设置management.metrics.data.repository.metric-name属性来自定义名称。

Repository接口和方法支持来自io.micrometer.core.Annotation包的@Timed批注。如果不想记录所有<代码>存储库调用的指标,可以将management.metrics.data.repository.autotime.enabled设置为FALSE,并独占使用@Timed注释。

A @Timed annotation with longTask = true enables a long task timer for the method. Long task timers require a separate metric name and can be stacked with a short task timer.

默认情况下,与存储库调用相关的指标使用以下信息进行标记:

Tag Description

存储库

存储库的简单类名。

方法

调用的存储库方法的名称。

结果状态(成功错误已取消正在运行)。

异常

从调用引发的任何异常的简单类名。

要替换默认标记,请提供实现RepositoryTagsProvider@Bean

7.3.16. RabbitMQ Metrics

自动配置支持使用名为rabbitmq的指标对所有可用的RabbitMQ连接工厂进行检测。

7.3.17. Spring Integration Metrics

只要有MeterRegistryBean,Spring集成就会自动提供微米支持。指标以spring.Integration.计量器名称发布。

7.3.18. Kafka Metrics

自动配置分别为自动配置的消费者工厂和生产者工厂注册MicrometerConsumer erListenerMicrometerProducerListener。它还为StreamsBuilderFactoryBean注册KafkaStreamsMicrometerListener。有关更多详细信息,请参阅Spring Kafka文档的微米原生指标部分。

7.3.19. MongoDB Metrics

本节简要介绍MongoDB的可用指标。

MongoDB Command Metrics

自动配置向自动配置的MongoClient注册一个MongoMetricsCommandListener

将为向底层MongoDB驱动程序发出的每个命令创建名为mongob.driver.Commands的计时器指标。默认情况下,每个指标都使用以下信息进行标记:

Tag Description

命令

发出的命令的名称。

cluster.id

向其发送命令的群集的标识符。

服务器地址

将命令发送到的服务器的地址。

状态

命令的结果(成功失败)。

要替换默认的指标标记,请定义一个MongoCommandTagsProviderBean,如下例所示:

Java
Kotlin
import io.micrometer.core.instrument.binder.mongodb.MongoCommandTagsProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyCommandTagsProviderConfiguration { @Bean public MongoCommandTagsProvider customCommandTagsProvider() { return new CustomCommandTagsProvider(); } } 
              
              

要禁用自动配置的命令指标,请设置以下属性:

Properties
Yaml
management.metrics.mongo.command.enabled=false
              
              
MongoDB Connection Pool Metrics

自动配置向自动配置的<MongoMetricsConnectionPoolListener>MongoClient注册代码。

为连接池创建了以下量度指标:

  • mongob.driver.pool.size报告连接池的当前大小,包括空闲成员和使用中成员。

  • mongob.driver.pool.check kedout报告当前正在使用的连接计数。

  • mongodb.driver.pool.waitqueuesize报告池中连接的等待队列的当前大小。

默认情况下,每个指标都使用以下信息进行标记:

Tag Description

cluster.id

连接池对应的群集的标识符。

服务器地址

连接池对应的服务器的地址。

要替换默认的指标标签,请定义一个MongoConnectionPoolTagsProviderBean:

Java
Kotlin
import io.micrometer.core.instrument.binder.mongodb.MongoConnectionPoolTagsProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyConnectionPoolTagsProviderConfiguration { @Bean public MongoConnectionPoolTagsProvider customConnectionPoolTagsProvider() { return new CustomConnectionPoolTagsProvider(); } } 
              
              

要禁用自动配置的连接池指标,请设置以下属性:

Properties
Yaml
management.metrics.mongo.connectionpool.enabled=false
              
              

7.3.20. Jetty Metrics

自动配置通过使用Microeter的JettyServerThreadPoolMetrics绑定Jetty的ThreadPool的指标。使用Microeter的JettyConnectionMetrics绑定Jetty的连接器实例的指标,当server.ssl.Enabled设置为true时,绑定Microeter的JettySslHandshakeMetrics

7.3.21. @Timed Annotation Support

要在Spring Boot不直接支持的地方使用@timed,请参考微米文档

7.3.22. Redis Metrics

自动配置为自动配置的LettuceConnectionFactory注册MicrometerCommandLatencyRecorder。有关更多详细信息,请参阅生菜文档的微米度量部分。

7.4. Registering Custom Metrics

要注册自定义指标,请将MeterRegistry注入您的组件:

Java
Kotlin
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tags; import org.springframework.stereotype.Component; @Component public class MyBean { private final Dictionary dictionary; public MyBean(MeterRegistry registry) { this.dictionary = Dictionary.load(); registry.gauge("dictionary.size", Tags.empty(), this.dictionary.getWords().size()); } } 
            
            

如果您的指标依赖于其他Bean,我们建议您使用MeterBinder注册它们:

Java
Kotlin
import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.binder.MeterBinder; import org.springframework.context.annotation.Bean; public class MyMeterBinderConfiguration { @Bean public MeterBinder queueSize(Queue queue) { return (registry) -> Gauge.builder("queueSize", queue::size).register(registry); } } 
            
            

使用MeterBinder可确保设置了正确的依赖关系,并且在检索度量值时Bean可用。如果您发现在组件或应用程序中重复检测一套指标,MeterBinder实现也很有用。

By default, metrics from all MeterBinder beans are automatically bound to the Spring-managed MeterRegistry.

7.5. Customizing Individual Metrics

如果您需要对特定Meter实例应用自定义设置,则可以使用io.micrometer.core.instrument.config.MeterFilter接口。

例如,如果您想将所有以com.ample开头的仪表ID的mytag.Region标记重命名为mytag.area,则可以执行以下操作:

Java
Kotlin
import io.micrometer.core.instrument.config.MeterFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyMetricsFilterConfiguration { @Bean public MeterFilter renameRegionTagMeterFilter() { return MeterFilter.renameTag("com.example", "mytag.region", "mytag.area"); } } 
            
            
By default, all MeterFilter beans are automatically bound to the Spring-managed MeterRegistry. Make sure to register your metrics by using the Spring-managed MeterRegistry and not any of the static methods on Metrics. These use the global registry that is not Spring-managed.

7.5.1. Common Tags

通用标签通常用于操作环境的维度向下钻取,如主机、实例、区域、堆栈等。Commons标记应用于所有仪表,并且可以配置,如下例所示:

Properties
Yaml
management.metrics.tags.region=us-east-1
management.metrics.tags.stack=prod
             
             

前面的示例将RegionStack标记分别添加到值为us-East-1prod的所有仪表。

The order of common tags is important if you use Graphite. As the order of common tags cannot be guaranteed by using this approach, Graphite users are advised to define a custom MeterFilter instead.

7.5.2. Per-meter Properties

除了MeterFilterBean之外,您还可以使用属性以每米为单位应用一组有限的定制。使用Spring Boot的PropertiesMeterFilter对以给定名称开头的任何仪表ID应用按仪表定制。下面的示例过滤掉ID以Example.Remote开头的所有仪表。

Properties
Yaml
management.metrics.enable.example.remote=false
             
             

以下属性允许按米自定义:

Table 1. Per-meter customizations
Property Description

Management.metrics.Enable

是否接受具有某些ID的仪表。不接受的仪表将从MeterRegistry中筛选出来。

management.metrics.distribution.percentiles-histogram

是否发布适用于计算可聚合(跨维)百分比近似值的直方图。

management.metrics.distribution.minimum-expected-valuemanagement.metrics.distribution.maximum-expected-value

通过限制预期值的范围来发布更少的直方图桶。

management.metrics.distribution.percentiles

发布在应用程序中计算的百分位值

management.metrics.distribution.expirymanagement.metrics.distribution.buffer-length

对最近的样本赋予更大的权重,方法是将它们累积到环形缓冲区中,这些缓冲区在可配置的超时后旋转,缓冲区长度可配置。

management.metrics.distribution.slo

发布累计直方图,其中包含由您的服务级别目标定义的存储桶。

有关百分位数-柱状图百分位数slo背后的概念的更多详细信息,请参阅千分尺文档的“柱状图和百分位数”部分。

7.6. Metrics Endpoint

Spring Boot提供了一个指标端点,您可以使用该端点进行诊断,以检查应用程序收集的指标。默认情况下,终结点不可用,必须公开。有关详细信息,请参阅暴露终结点

导航到/Actuator/Metrics将显示可用仪表名称的列表。您可以通过提供特定仪表的名称作为选择器/actuator/metrics/jvm.memory.max.- - 来深入查看有关该仪表的信息

您在这里使用的名称应该与代码中使用的名称匹配,而不是在命名之后的名称--为其发送到的监控系统标准化的约定。换句话说,如果jvm.ememy.max由于其蛇壳命名约定而在Prometheus中显示为jvm_Memory_max,那么在指标端点中检查仪表时,您仍然应该使用jvm.ememy.max作为选择器。

您还可以在URL的末尾添加任意数量的TAG=KEY:VALUE查询参数,以在维度上向下钻取仪表/actuator/metrics/jvm.memory.max?tag=area:nonheap.- - 

报告的测量值是匹配计量器名称的所有计量器和已应用的任何标记的统计数据的总和。在前面的示例中,返回的统计信息是堆的“代码缓存”、“压缩类空间”和“元空间”区域的最大内存占用之和。如果您只想查看“metspace”的最大大小,可以添加一个额外的tag=id:metspace/actuator/metrics/jvm.memory.max?tag=area:nonheap&;tag=id:Metaspace.- - 

7.7. Integration with Micrometer Observation

DefaultMeterObservationHandlerObservationRegistry上自动注册,这将为每个已完成的观测创建指标。

8. Tracing

Spring Boot Actuator为微米跟踪提供依赖管理和自动配置,这是流行跟踪库的外观。

To learn more about Micrometer Tracing capabilities, see its reference documentation.

8.1. Supported Tracers

Spring Boot提供了以下跟踪器的自动配置:

8.2. Getting Started

我们需要一个示例应用程序,我们可以使用它来开始跟踪。就我们的目的而言,简单的“Hello World!”“Get-started.html一节中介绍的Web应用程序就足够了。我们将使用Open遥测跟踪器和Zipkin作为跟踪后端。

简单地说,我们的主要应用程序代码如下所示:

import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class MyApplication { private static final Log logger = LogFactory.getLog(MyApplication.class); @RequestMapping("/") String home() { logger.info("home() has been called"); return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } 
            
            
There’s an added logger statement in the home() method, which will be important later.

现在,我们必须添加以下依赖项:

  • org.springframework.boot:spring-boot-starter-actuator

  • io.micrometer:micrometer-tracing-bridge-otel-它是将微米观测API连接到OpenTelemeter所需的。

  • io.opentelemetry:opentelemetry-exporter-zipkin-向Zipkin报告跟踪所需的。

添加以下应用程序属性:

Properties
Yaml
management.tracing.sampling.probability=1.0
            
            

默认情况下,Spring Boot仅对10%的请求进行采样,以防止超出跟踪后端。该属性将其切换为100%,以便将每个请求发送到跟踪后端。

为了收集和可视化跟踪,我们需要一个运行跟踪后端。我们在这里使用Zipkin作为跟踪后端。Zipkin快速入门指南提供如何在本地启动Zipkin的说明。

在Zipkin运行后,您可以启动应用程序。

如果您打开Web浏览器进入localhost:8080,您应该会看到以下输出:

Hello World!

在幕后,已经为HTTP请求创建了观察,而该HTTP请求又被桥接到OpenTelemeter,后者向Zipkin报告新的跟踪。

现在,在localhost:9411中打开Zipkin UI,然后按“Run Query”按钮列出所有收集到的跟踪。你应该看到一条痕迹。按“Show”按钮可查看该轨迹的详细信息。

You can include the current trace and span id in the logs by setting the logging.pattern.level property to %5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]

8.3. Tracer Implementations

由于千分尺追踪器支持多个追踪器实现,因此Spring Boot支持多种依赖项组合。

所有跟踪器实现都需要org.springframework.boot:spring-boot-starter-actuator依赖项。

8.3.1. OpenTelemetry With Zipkin

  • io.micrometer:micrometer-tracing-bridge-otel-它是将微米观测API嫁接到OpenTelemeter所必需的。

  • io.opentelemetry:opentelemetry-exporter-zipkin-需要它来向Zipkin报告痕迹。

8.3.2. OpenTelemetry With Wavefront

  • io.micrometer:micrometer-tracing-bridge-otel-它是将微米观测API嫁接到OpenTelemeter所必需的。

  • io.micrometer:micrometer-tracing-reporter-wavefront-需要它来向Wavefront报告踪迹。

8.3.3. OpenZipkin Brave With Zipkin

  • io.micrometer:micrometer-tracing-bridge-brave-将微米观测应用编程接口连接到Brave所需的。

  • io.zipkin.reporter2:zipkin-reporter-brave-需要它来向Zipkin报告痕迹。

If your project doesn’t use Spring MVC or Spring WebFlux, the io.zipkin.reporter2:zipkin-sender-urlconnection dependency is needed, too.

8.3.4. OpenZipkin Brave With Wavefront

  • io.micrometer:micrometer-tracing-bridge-brave-将微米观测应用编程接口连接到Brave所需的。

  • io.micrometer:micrometer-tracing-reporter-wavefront-需要它来向Wavefront报告踪迹。

8.4. Integration with Micrometer Observation

代码自动注册在<TracingAwareMeterObservationHandler>ObservationRegistry上,这将为每个已完成的观测创建跨度。

8.5. Creating Custom Spans

您可以通过开始观测来创建自己的跨度。为此,将ObservationRegistry注入您的组件:

import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import org.springframework.stereotype.Component; @Component class CustomObservation { private final ObservationRegistry observationRegistry; CustomObservation(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } void someOperation() { Observation observation = Observation.createNotStarted("some-operation", this.observationRegistry); observation.lowCardinalityKeyValue("some-tag", "some-value"); observation.observe(() -> { // Business logic ... }); } } 
            
            

这将创建一个名为“Some-OPERATION”的观察,标记为“Some-tag=Some-Value”。

If you want to create a span without creating a metric, you need to use the lower-level Tracer API from Micrometer.

9. Auditing

一旦使用了Spring Security,Spring Boot Actuator就有了一个灵活的审计框架,可以发布事件(默认情况下,“身份验证成功”、“失败”和“访问被拒绝”异常)。此功能对于报告和实施基于身份验证失败的锁定策略非常有用。

您可以通过在应用程序的配置中提供类型为AuditEventRepository的Bean来启用审计。为了方便起见,Spring Boot提供了一个InMemoyAuditEventRepositoryInMhemyAuditEventRepository功能有限,建议仅在开发环境中使用。对于生产环境,请考虑创建您自己的替代AuditEventRepository实现。

9.1. Custom Auditing

要定制已发布的安全事件,您可以提供自己的AbstractAuthenticationAuditListenerAbstractAuthorizationAuditListener.实现

您还可以将审计服务用于您自己的业务事件。为此,要么将AuditEventRepositoryBean注入您自己的组件并直接使用,要么使用SpringApplicationEventPublisher发布AuditApplicationEvent(通过实现ApplicationEventPublisherAware)。

10. Recording HTTP Exchanges

您可以通过在应用程序的配置中提供HttpExchangeRepository类型的Bean来启用对HTTP交换的记录。为了方便起见,Spring Boot提供了InMemoyHttpExchangeRepository,默认情况下,它存储最后100个请求-响应交换。InMemory HttpExchangeRepository与跟踪解决方案相比有一定限制,我们建议仅将其用于开发环境。对于生产环境,我们建议使用可用于生产的跟踪或可观察性解决方案,如Zipkin或OpenTelemeter。或者,您可以创建自己的HttpExchangeRepository

您可以使用HTTPExchange终结点来获取有关HttpExchangeRepository中存储的请求-响应交换的信息。

10.1. Custom HTTP Exchange Recording

若要自定义每个记录的交换中包含的项,请使用management.httpexchanges.recording.include配置属性。

要完全禁用重新编码,请将management.httpexchanges.recording.enabled设置为FALSE

11. Process Monitoring

SpringBoot模块中,您可以找到两个类来创建通常用于进程监控的文件:

  • ApplicationPidFileWriter创建一个包含应用程序ID的文件(默认情况下,在应用程序目录中,文件名为Application.id)。

  • WebServerPortFileWriter创建包含正在运行的Web服务器的端口的一个或多个文件(默认情况下,在应用程序目录中,文件名为Application.port)。

默认情况下,这些编写器不会激活,但您可以启用它们:

11.1. Extending Configuration

META-INF/spring.Factory文件中,您可以激活一个或多个编写PID文件的监听器:

org.springframework.context.ApplicationListener=\
org.springframework.boot.context.ApplicationPidFileWriter,\
org.springframework.boot.web.context.WebServerPortFileWriter

11.2. Programmatically Enabling Process Monitoring

还可以通过调用SpringApplication.addListeners(…)来激活监听器​)方法,并传递相应的编写器对象。此方法还允许您在Writer构造函数中自定义文件名和路径。

12. Cloud Foundry Support

Spring Boot的执行器模块包括当您部署到兼容的Cloud Foundry实例时激活的附加支持。/cloudfindryapplication路径提供了到所有@EndpointBean的替代安全路由。

扩展的支持允许使用Spring Boot执行器信息来扩展Cloud Foundry管理UI(例如,您可以用来查看已部署的应用程序的Web应用程序)。例如,应用程序状态页可以包括完整的运行状况信息,而不是典型的“正在运行”或“已停止”状态。

The /cloudfoundryapplication path is not directly accessible to regular users. To use the endpoint, you must pass a valid UAA token with the request.

12.1. Disabling Extended Cloud Foundry Actuator Support

如果要完全禁用/CloudFundryApplication终结点,可以将以下设置添加到您的应用程序属性文件中:

Properties
Yaml
management.cloudfoundry.enabled=false
            
            

12.2. Cloud Foundry Self-signed Certificates

默认情况下,/CloudFounddryApplication端点的安全验证会对各种Cloud Foundry服务进行SSL调用。如果您的Cloud Foundry UAA或云控制器服务使用自签名证书,则需要设置以下属性:

Properties
Yaml
management.cloudfoundry.skip-ssl-validation=true
            
            

12.3. Custom Context Path

如果服务器的上下文路径被配置为/以外的任何内容,则Cloud Foundry端点在应用程序的根目录下不可用。例如,如果server.servlet.context-path=/app,Cloud Foundry端点位于<代码>/APP/CloudFounddryApplication/*

如果您希望Cloud Foundry端点在/cloudfindryapplication/*中始终可用,而不管服务器的上下文路径如何,那么您需要在您的应用程序中显式配置它。根据使用的Web服务器的不同,配置会有所不同。对于Tomcat,您可以添加以下配置:

Java
Kotlin
import java.io.IOException; import java.util.Collections; import jakarta.servlet.GenericServlet; import jakarta.servlet.Servlet; import jakarta.servlet.ServletContainerInitializer; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.apache.catalina.Host; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MyCloudFoundryConfiguration { @Bean public TomcatServletWebServerFactory servletWebServerFactory() { return new TomcatServletWebServerFactory() { @Override protected void prepareContext(Host host, ServletContextInitializer[] initializers) { super.prepareContext(host, initializers); StandardContext child = new StandardContext(); child.addLifecycleListener(new Tomcat.FixContextListener()); child.setPath("/cloudfoundryapplication"); ServletContainerInitializer initializer = getServletContextInitializer(getContextPath()); child.addServletContainerInitializer(initializer, Collections.emptySet()); child.setCrossContext(true); host.addChild(child); } }; } private ServletContainerInitializer getServletContextInitializer(String contextPath) { return (classes, context) -> { Servlet servlet = new GenericServlet() { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { ServletContext context = req.getServletContext().getContext(contextPath); context.getRequestDispatcher("/cloudfoundryapplication").forward(req, res); } }; context.addServlet("cloudfoundry", servlet).addMapping("/*"); }; } } 
            
            

13. What to Read Next

您可能需要阅读Graphite等绘图工具。

否则,您可以继续阅读“部署选项”,或者跳转到有关Spring Boot的构建工具插件的深入信息。