53. Endpoints

Actuator 端点使您可以监视应用程序并与之交互。 Spring Boot 包含许多内置端点,可让您添加自己的端点。例如,health端点提供基本的应用程序运行状况信息。

每个端点可以是启用或禁用。这控制了是否创建了端点以及它的 bean 在应用程序上下文中是否存在。要远程访问,端点也必须是通过 JMX 或 HTTP 公开。大多数应用程序选择 HTTP,其中终结点的 ID 和前缀/actuatorMap 到 URL。例如,默认情况下,health端点 Map 到/actuator/health

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

IDDescription默认启用
auditevents公开当前应用程序的审核事件信息。Yes
beans显示应用程序中所有 Spring Bean 的完整列表。Yes
caches公开可用的缓存。Yes
conditions显示在配置和自动配置类上评估的条件以及它们匹配或不匹配的原因。Yes
configprops显示所有@ConfigurationProperties的整理列表。Yes
env从 Spring 的ConfigurableEnvironment公开属性。Yes
flyway显示已应用的所有 Flyway 数据库迁移。Yes
health显示应用程序运行状况信息。Yes
httptrace显示 HTTP 跟踪信息(默认情况下,最近 100 个 HTTP 请求-响应交换)。Yes
info显示任意应用程序信息。Yes
integrationgraph显示 Spring Integration 图。Yes
loggers显示和修改应用程序中 Logger 的配置。Yes
liquibase显示已应用的所有 Liquibase 数据库迁移。Yes
metrics显示当前应用程序的“Metrics”信息。Yes
mappings显示所有@RequestMapping路径的整理列表。Yes
scheduledtasks显示应用程序中的计划任务。Yes
sessions允许从 Spring Session 支持的会话存储中检索和删除用户会话。使用 Spring Session 对反应式 Web 应用程序的支持时不可用。Yes
shutdown使应用程序正常关闭。No
threaddump执行线程转储。Yes

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

IDDescription默认启用
heapdump返回一个hprof堆转储文件。Yes
jolokia通过 HTTP 公开 JMX bean(当 Jolokia 在 Classpath 上时,不适用于 WebFlux)。Yes
logfile返回日志文件的内容(如果已设置logging.filelogging.path属性)。支持使用 HTTP RangeHeaders 来检索部分日志文件的内容。Yes
prometheus以 Prometheus 服务器可以抓取的格式公开 Metrics。Yes

要了解有关 Actuator 端点及其请求和响应格式的更多信息,请参阅单独的 API 文档(HTMLPDF)。

53.1 启用端点

默认情况下,除shutdown之外的所有端点均处于启用状态。要配置端点的启用,请使用其management.endpoint.<id>.enabled属性。以下示例启用shutdown端点:

management.endpoint.shutdown.enabled=true

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

management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true

Note

禁用的端点将从应用程序上下文中完全删除。如果您只想更改端点公开的技术,请改用包含和排除属性

53.2 公开端点

由于端点可能包含敏感信息,因此应谨慎考虑何时公开它们。下表显示了内置端点的默认暴露:

IDJMXWeb
auditeventsYesNo
beansYesNo
cachesYesNo
conditionsYesNo
configpropsYesNo
envYesNo
flywayYesNo
healthYesYes
heapdumpN/ANo
httptraceYesNo
infoYesYes
integrationgraphYesNo
jolokiaN/ANo
logfileN/ANo
loggersYesNo
liquibaseYesNo
metricsYesNo
mappingsYesNo
prometheusN/ANo
scheduledtasksYesNo
sessionsYesNo
shutdownYesNo
threaddumpYesNo

要更改公开哪些端点,请使用以下特定于技术的includeexclude属性:

PropertyDefault
management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include*
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.includeinfo, health

include属性列出了公开的端点的 ID。 exclude属性列出了不应公开的端点的 ID。 exclude属性优先于include属性。 includeexclude属性都可以使用端点 ID 列表进行配置。

例如,要停止通过 JMX 公开所有端点,而仅公开healthinfo端点,请使用以下属性:

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

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

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans

Note

*在 YAML 中具有特殊含义,因此,如果要包括(或排除)所有端点,请确保添加引号,如以下示例所示:

management:
endpoints:
web:
exposure:
include: "*"

Note

如果您的申请公开公开,我们强烈建议您也保护您的端点

Tip

如果要针对暴露端点的时间实施自己的策略,则可以注册EndpointFilter bean。

53.3 保护 HTTP 端点

您应该像对待其他任何敏感 URL 一样,小心保护 HTTP 端点的安全。如果存在 Spring Security,则默认情况下使用 Spring Security 的内容协商策略保护端点的安全。例如,如果您希望为 HTTP 端点配置自定义安全性,只允许具有特定角色的用户访问它们,Spring Boot 提供了一些方便的RequestMatcher对象,可以将它们与 Spring Security 结合使用。

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

@Configuration
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
				.anyRequest().hasRole("ENDPOINT_ADMIN")
				.and()
			.httpBasic();
	}

}

前面的示例使用EndpointRequest.toAnyEndpoint()将请求匹配到任何端点,然后确保所有角色都具有ENDPOINT_ADMIN角色。 EndpointRequest上还有其他几种匹配器方法。有关详细信息,请参见 API 文档(HTMLPDF)。

如果将应用程序部署在防火墙后面,则可能希望可以在不进行身份验证的情况下访问所有 Actuator 端点。您可以通过更改management.endpoints.web.exposure.include属性来做到这一点,如下所示:

application.properties.

management.endpoints.web.exposure.include=*

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

@Configuration
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
			.anyRequest().permitAll();
	}

}

53.4 配置端点

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

application.properties.

management.endpoint.beans.cache.time-to-live=10s

Note

前缀management.endpoint.<name>用于唯一标识正在配置的端点。

Note

发出经过身份验证的 HTTP 请求时,Principal被视为端点的 Importing,因此将不缓存响应。

53.5 用于 Actuator Web 端点的超媒体

添加了“发现页面”以及指向所有端点的链接。默认情况下,“发现页面”在/actuator上可用。

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

53.6 CORS 支持

跨域资源共享(CORS)是W3C specification,它使您可以灵活地指定授权哪种类型的跨域请求。如果使用 Spring MVC 或 Spring WebFlux,则可以将 Actuator 的 Web 端点配置为支持此类方案。

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

management.endpoints.web.cors.allowed-origins=http://example.com
management.endpoints.web.cors.allowed-methods=GET,POST

Tip

有关选项的完整列表,请参见CorsEndpointProperties

53.7 实施自定义端点

如果添加带有@EndpointComments 的@Bean,则带有@ReadOperation@WriteOperation@DeleteOperationComments 的任何方法都将通过 JMX 以及 Web 应用程序中的 HTTP 自动公开。可以使用 Jersey,Spring MVC 或 Spring WebFlux 通过 HTTP 公开端点。

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

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

最后,如果您需要访问特定于 Web 框架的功能,则可以实现 Servlet 或 Spring @Controller@RestController端点,但代价是它们无法通过 JMX 或使用其他 Web 框架使用。

53.7.1 接收 Importing

端点上的操作通过其参数接收 Importing。通过网络公开时,这些参数的值取自 URL 的查询参数和 JSON 请求正文。通过 JMX 公开时,参数将 Map 到 MBean 操作的参数。默认情况下,参数是必需的。可以通过使用@org.springframework.lang.Nullable对其进行 Comments 来使它们成为可选的。

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

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

这可用于调用采用String nameint counter参数的写操作。

Tip

由于端点与技术无关,因此只能在方法签名中指定简单类型。特别是,不支持使用定义namecounter属性的自定义类型声明单个参数。

Note

为了将 ImportingMap 到操作方法的参数,实现端点的 Java 代码应使用-parameters编译,而实现端点的 Kotlin 代码应使用-java-parameters编译。如果您使用的是 Spring Boot 的 Gradle 插件,或者您使用的是 Maven 和spring-boot-starter-parent,那么这将自动发生。

Importing 类型转换

如有必要,传递给端点操作方法的参数会自动转换为所需的类型。在调用操作方法之前,使用ApplicationConversionService实例将通过 JMX 或 HTTP 请求接收的 Importing 转换为所需的类型。

53.7.2 自定义 Web 端点

使用 Jersey,Spring MVC 或 Spring WebFlux 通过 HTTP 自动公开@Endpoint@WebEndpoint@EndpointWebExtension上的操作。

Web 端点请求谓词

对于在暴露于 Web 的端点上的每个操作,都会自动生成一个请求谓词。

Path

谓词的路径由终结点的 ID 和暴露于 Web 的终结点的基本路径确定。默认基本路径为/actuator。例如,ID 为sessions的端点将使用/actuator/sessions作为其在谓词中的路径。

通过使用@SelectorComments 操作方法的一个或多个参数,可以进一步自定义路径。将这样的参数作为路径变量添加到路径谓词。当端点操作被调用时,变量的值被传递到操作方法中。

HTTP method

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

OperationHTTP method
@ReadOperationGET
@WriteOperationPOST
@DeleteOperationDELETE

Consumes

对于使用请求正文的@WriteOperation(HTTP POST),谓词的消耗子句为application/vnd.spring-boot.actuator.v2+json, application/json。对于所有其他操作,消耗子句为空。

Produces

谓词的 Produces 子句可以由@DeleteOperation@ReadOperation@WriteOperation注解的produces属性确定。该属性是可选的。如果未使用,则会自动确定 produces 子句。

如果操作方法返回voidVoid,则 produces 子句为空。如果操作方法返回org.springframework.core.io.Resource,则 Produces 子句为application/octet-stream。对于所有其他操作,produces 子句为application/vnd.spring-boot.actuator.v2+json, application/json

Web 端点响应状态

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

@ReadOperation返回一个值,响应状态将为 200(确定)。如果未返回值,则响应状态将为 404(未找到)。

如果@WriteOperation@DeleteOperation返回值,则响应状态将为 200(确定)。如果未返回值,则响应状态将为 204(无内容)。

如果在没有必需参数或无法将参数转换为必需类型的参数的情况下调用操作,则不会调用该操作方法,并且响应状态将为 400(错误请求)。

Web 端点范围请求

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

Note

使用 Jersey 时不支持范围请求。

Web 端点安全

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

53.7.3 Servlet 端点

通过实现带有@ServletEndpointComments 的类(也可以实现Supplier<EndpointServlet>),可以将Servlet公开为端点。 Servlet 端点提供了与 Servlet 容器的更深层集成,但以可移植性为代价。它们旨在用于将现有的Servlet公开为端点。对于新端点,应尽可能使用@Endpoint@WebEndpoint注解。

53.7.4 控制器端点

@ControllerEndpoint@RestControllerEndpoint可用于实现仅由 Spring MVC 或 Spring WebFlux 公开的端点。使用 Spring MVC 和 Spring WebFlux 的标准 Comments(例如@RequestMapping@GetMapping)Map 方法,并将端点的 ID 用作路径的前缀。控制器端点提供了与 Spring Web 框架的更深层集成,但以可移植性为代价。尽可能使用@Endpoint@WebEndpoint注解。

53.8 健康信息

您可以使用运行状况信息来检查正在运行的应用程序的状态。监视软件通常使用它在生产系统出现故障时向某人发出警报。 health端点公开的信息取决于management.endpoint.health.show-details属性,该属性可以配置以下值之一:

NameDescription
never详细信息永远不会显示。
when-authorized详细信息仅显示给授权用户。可以使用management.endpoint.health.roles配置授权角色。
always向所有用户显示详细信息。

默认值为never。当用户担任一个或多个端点的角色时,该用户被视为已授权。如果端点没有配置的角色(默认值),则所有通过身份验证的用户均被视为已授权。可以使用management.endpoint.health.roles属性配置角色。

Note

如果您已保护应用程序安全并希望使用always,则安全配置必须允许经过身份验证的用户和未经身份验证的用户都可以访问运行状况端点。

运行状况信息是从HealthIndicatorRegistry的内容中收集的(默认情况下,ApplicationContext中定义的所有HealthIndicator实例。Spring Boot 包含许多自动配置的HealthIndicators,您也可以编写自己的实例。默认情况下,最终的系统状态由HealthAggregator根据状态的有序列表对每个HealthIndicator的状态进行排序。排序后的列表中的第一个状态用作整体运行状况。如果没有HealthIndicator返回HealthAggregator已知的状态,则使用UNKNOWN状态。

Tip

HealthIndicatorRegistry可用于在运行时注册和注销运行状况指示器。

53.8.1 自动配置的健康 Metrics

适当时,Spring Boot 会自动配置以下HealthIndicators

NameDescription
CassandraHealthIndicator检查 Cassandra 数据库是否已启动。
CouchbaseHealthIndicator检查 Couchbase 群集是否已启动。
DiskSpaceHealthIndicator检查磁盘空间不足。
DataSourceHealthIndicator检查是否可以构建到DataSource的连接。
ElasticsearchHealthIndicator检查 Elasticsearch 集群是否已启动。
InfluxDbHealthIndicator检查 InfluxDB 服务器是否已启动。
JmsHealthIndicator检查 JMS 代理是否启动。
MailHealthIndicator检查邮件服务器是否已启动。
MongoHealthIndicator检查 Mongo 数据库是否已启动。
Neo4jHealthIndicator检查 Neo4j 服务器是否已启动。
RabbitHealthIndicator检查 Rabbit 服务器是否已启动。
RedisHealthIndicator检查 Redis 服务器是否启动。
SolrHealthIndicator检查 Solr 服务器是否已启动。

Tip

您可以通过设置management.health.defaults.enabled属性来全部禁用它们。

53.8.2 编写自定义健康 Metrics

要提供自定义健康信息,您可以注册实现HealthIndicator接口的 Spring bean。您需要提供health()方法的实现并返回Health响应。 Health响应应包含状态,并且可以选择包含要显示的其他详细信息。以下代码显示了示例HealthIndicator实现:

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(); // perform some specific health check
		if (errorCode != 0) {
			return Health.down().withDetail("Error Code", errorCode).build();
		}
		return Health.up().build();
	}

}

Note

给定HealthIndicator的标识符是不带HealthIndicator后缀的 bean 的名称(如果存在)。在前面的示例中,健康信息在名为my的条目中可用。

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

例如,假设在您的HealthIndicator实现中使用了新的Status代码FATAL。要配置严重性 Sequences,请将以下属性添加到您的应用程序属性中:

management.health.status.order=FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP

响应中的 HTTP 状态代码反映了总体健康状态(例如UPMap 为 200,而OUT_OF_SERVICEDOWNMap 为 503)。如果通过 HTTP 访问运行状况终结点,则可能还需要注册自定义状态 Map。例如,以下属性将FATALMap 到 503(服务不可用):

management.health.status.http-mapping.FATAL=503

Tip

如果需要更多控制,则可以定义自己的HealthStatusHttpMapper bean。

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

StatusMapping
DOWNSERVICE_UNAVAILABLE (503)
OUT_OF_SERVICESERVICE_UNAVAILABLE (503)
UP默认情况下没有 Map,因此 http 状态为 200
UNKNOWN默认情况下没有 Map,因此 http 状态为 200

53.8.3 Reactive 健康 Metrics

对于响应式应用程序,例如使用 Spring WebFlux 的应用程序,ReactiveHealthIndicator提供了非阻塞 Contract 以获取应用程序的运行状况。与传统HealthIndicator相似,健康信息是从ReactiveHealthIndicatorRegistry的内容中收集的(默认情况下,在ApplicationContext中定义的所有HealthIndicatorReactiveHealthIndicator实例。常规HealthIndicator不会根据反应式 API 进行检查,都是在弹性调度程序上执行的。

Tip

在响应式应用程序中,ReactiveHealthIndicatorRegistry可用于在运行时注册和注销运行状况指示器。

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

@Component
public class MyReactiveHealthIndicator implements ReactiveHealthIndicator {

	@Override
	public Mono<Health> health() {
		return doHealthCheck() //perform some specific health check that returns a Mono<Health>
			.onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build())));
	}

}

Tip

要自动处理错误,请考虑从AbstractReactiveHealthIndicator扩展。

53.8.4 自动配置的 ReactiveHealthIndicators

适当时,Spring Boot 会自动配置以下ReactiveHealthIndicators

NameDescription
CassandraReactiveHealthIndicator检查 Cassandra 数据库是否已启动。
CouchbaseReactiveHealthIndicator检查 Couchbase 群集是否已启动。
MongoReactiveHealthIndicator检查 Mongo 数据库是否已启动。
RedisReactiveHealthIndicator检查 Redis 服务器是否启动。

Tip

如有必要,可用无功指示器代替常规指示器。另外,任何未明确处理的HealthIndicator都会自动包装。

53.9 申请信息

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

53.9.1 自动配置的信息贡献者

适当时,Spring Boot 会自动配置以下InfoContributor bean:

NameDescription
EnvironmentInfoContributorinfo键下公开Environment中的任何键。
GitInfoContributor如果git.properties文件可用,则公开 git 信息。
BuildInfoContributor如果META-INF/build-info.properties文件可用,则公开构建信息。

Tip

通过设置management.info.defaults.enabled属性,可以全部禁用它们。

53.9.2 自定义应用程序信息

您可以通过设置info.* Spring 属性来自定义info终结点公开的数据。 info键下的所有Environment属性将自动显示。例如,您可以将以下设置添加到application.properties文件中:

info.app.encoding=UTF-8
info.app.java.source=1.8
info.app.java.target=1.8

Tip

除了对这些值进行硬编码,您还可以在构建时扩展信息属性

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

info.app.encoding[emailprotected]@
info.app.java.source[emailprotected]@
info.app.java.target[emailprotected]@

53.9.3 Git 提交信息

info端点的另一个有用功能是,它可以在项目构建时发布有关git源代码存储库状态的信息。如果GitProperties bean 可用,则公开git.branchgit.commit.idgit.commit.time属性。

Tip

如果git.properties文件在 Classpath 的根目录中可用,则会自动配置GitProperties bean。有关更多详细信息,请参见“ 生成 git 信息”。

如果要显示完整的 git 信息(即git.properties的完整内容),请使用management.info.git.mode属性,如下所示:

management.info.git.mode=full

53.9.4 生成信息

如果有BuildProperties bean,则info端点也可以发布有关构建的信息。如果META-INF/build-info.properties文件在 Classpath 中可用,则会发生这种情况。

Tip

Maven 和 Gradle 插件都可以生成该文件。有关更多详细信息,请参见“ 生成构建信息”。

53.9.5 编写自定义信息提供者

要提供自定义应用程序信息,您可以注册实现InfoContributor接口的 Spring bean。

下面的示例使用单个值贡献一个example条目:

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 ExampleInfoContributor implements InfoContributor {

	@Override
	public void contribute(Info.Builder builder) {
		builder.withDetail("example",
				Collections.singletonMap("key", "value"));
	}

}

如果到达info端点,则应该看到包含以下附加条目的响应:

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