Endpoints
Actuator 端点让您监控和交互您的应用程序。Spring Boot 包含许多内置端点,并让您可以添加您自己的端点。例如,health
端点提供基本的应用程序健康状况信息。
Actuator endpoints let you monitor and interact with your application.
Spring Boot includes a number of built-in endpoints and lets you add your own.
For example, the health
endpoint provides basic application health information.
您可以 enable or disable 每个单独的端点和 expose them (make them remotely accessible) over HTTP or JMX。当端点既启用又能公开时,它将被视为可用。内置端点仅在可用时才自动配置。大多数应用程序选择公开 HTTP,其中端点的 ID 和 /actuator
的前缀被映射到 URL。例如,默认情况下,health
端点被映射到 /actuator/health
。
You can enable or disable each individual endpoint and expose them (make them remotely accessible) over HTTP or JMX.
An endpoint is considered to be available when it is both enabled and exposed.
The built-in endpoints are auto-configured only when they are available.
Most applications choose exposure over HTTP, where the ID of the endpoint and a prefix of /actuator
is mapped to a URL.
For example, by default, the health
endpoint is mapped to /actuator/health
.
若要了解有关 Actuator 的端点及其请求和响应格式的更多信息,请参阅 API documentation。 |
To learn more about the Actuator’s endpoints and their request and response formats, see the API documentation. |
以下技术不可知端点可用:
The following technology-agnostic endpoints are available:
ID | Description |
---|---|
|
Exposes audit events information for the current application.
Requires an |
|
Displays a complete list of all the Spring beans in your application. |
|
Exposes available caches. |
|
Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match. |
|
Displays a collated list of all |
|
Exposes properties from Spring’s |
|
Shows any Flyway database migrations that have been applied.
Requires one or more |
|
Shows application health information. |
|
Displays HTTP exchange information (by default, the last 100 HTTP request-response exchanges).
Requires an |
|
Displays arbitrary application info. |
|
Shows the Spring Integration graph.
Requires a dependency on |
|
Shows and modifies the configuration of loggers in the application. |
|
Shows any Liquibase database migrations that have been applied.
Requires one or more |
|
Shows “metrics” information for the current application. |
|
Displays a collated list of all |
|
Shows information about Quartz Scheduler jobs. Subject to sanitization. |
|
Displays the scheduled tasks in your application. |
|
Allows retrieval and deletion of user sessions from a Spring Session-backed session store. Requires a servlet-based web application that uses Spring Session. |
|
Lets the application be gracefully shutdown. Only works when using jar packaging. Disabled by default. |
|
Shows the startup steps data collected by the |
|
Performs a thread dump. |
如果您的应用程序是 Web 应用程序(Spring MVC、Spring WebFlux 或 Jersey),则可以使用以下附加端点:
If your application is a web application (Spring MVC, Spring WebFlux, or Jersey), you can use the following additional endpoints:
ID | Description |
---|---|
|
Returns a heap dump file.
On a HotSpot JVM, an |
|
Returns the contents of the logfile (if the |
|
Exposes metrics in a format that can be scraped by a Prometheus server.
Requires a dependency on |
Enabling Endpoints
在默认情况下,除“@1”之外的所有端点都会启用。要配置端点的启用状态,可以使用“@2”属性。以下示例启用“@3”端点:
By default, all endpoints except for shutdown
are enabled.
To configure the enablement of an endpoint, use its management.endpoint.<id>.enabled
property.
The following example enables the shutdown
endpoint:
management: endpoint: shutdown: enabled: true
如果您更喜欢先注销再启用端点,而不是先启用再注销,请将“configprop:management.endpoints.enabled-by-default[]”属性设置为“@4”,然后使用单个端点“@5”属性重新启用。以下示例启用“@6”端点并禁用所有其他端点:
If you prefer endpoint enablement to be opt-in rather than opt-out, set the configprop:management.endpoints.enabled-by-default[] property to false
and use individual endpoint enabled
properties to opt back in.
The following example enables the info
endpoint and disables all other endpoints:
management: endpoints: enabled-by-default: false endpoint: info: enabled: true
禁用的端点会从应用程序上下文中完全移除。如果您只想更改端点的公开技术,请使用“@9”。 |
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 |
Exposing Endpoints
在默认情况下,只有状态端点公开在 HTTP 和 JMX 中,由于端点可能包含敏感信息,因此您是否公开它们时应仔细考虑。
By default, only the health endpoint is exposed over HTTP and JMX. Since Endpoints may contain sensitive information, you should carefully consider when to expose them.
要更改公开哪些端点,请使用以下特定于技术的“@10”和“@11”属性:
To change which endpoints are exposed, use the following technology-specific include
and exclude
properties:
Property | Default |
---|---|
configprop:management.endpoints.jmx.exposure.exclude[] |
|
configprop:management.endpoints.jmx.exposure.include[] |
|
configprop:management.endpoints.web.exposure.exclude[] |
|
configprop:management.endpoints.web.exposure.include[] |
|
“@12”属性列出公开的端点的 ID。"@13" 属性列出不应该公开的端点的 ID。"“@14”属性优先于“@15”属性。您可以使用端点 ID 清单配置“@16”属性和“@17”属性。
The include
property lists the IDs of the endpoints that are exposed.
The exclude
property lists the IDs of the endpoints that should not be exposed.
The exclude
property takes precedence over the include
property.
You can configure both the include
and the exclude
properties with a list of endpoint IDs.
例如,要只在 JMX 中公开“@18”和“@19”端点,请使用以下属性:
For example, to only expose the health
and info
endpoints over JMX, use the following property:
management: endpoints: jmx: exposure: include: "health,info"
“@20”可用于选择所有端点。例如,要在 HTTP 中公开除了“@21”和“@22”端点之外的所有内容,请使用以下属性:
*
can be used to select all endpoints.
For example, to expose everything over HTTP except the env
and beans
endpoints, use the following properties:
management: endpoints: web: exposure: include: "*" exclude: "env,beans"
“@23”在 YAML 中有特殊含义,因此如果您要包含(或排除)所有端点,请务必添加引号。 |
|
如果您的应用程序公开,我们强烈建议您也“@24”。 |
If your application is exposed publicly, we strongly recommend that you also secure your endpoints. |
如果您要实施端点公开的自定义策略,则可以注册一个“@25”bean。 |
If you want to implement your own strategy for when endpoints are exposed, you can register an |
Security
出于安全目的,只有“@26”端点在默认情况下公开在 HTTP 中。您可以使用“configprop:management.endpoints.web.exposure.include[]”属性配置公开的端点。
For security purposes, only the /health
endpoint is exposed over HTTP by default.
You can use the configprop:management.endpoints.web.exposure.include[] property to configure the endpoints that are exposed.
在设置“@27”之前,请确保公开的致动器不包含敏感信息,并受到防火墙或 Spring 安全性等保护。 |
Before setting the |
如果 Spring 安全性在类路径上,并且不存在其他“@28”bean,那么除了“@29”之外的所有致动器都受 Spring Boot 自动配置保护。如果您定义一个自定义“@30”bean,Spring Boot 自动配置会退场,让您完全控制致动器访问规则。
If Spring Security is on the classpath and no other SecurityFilterChain
bean is present, all actuators other than /health
are secured by Spring Boot auto-configuration.
If you define a custom SecurityFilterChain
bean, Spring Boot auto-configuration backs off and lets you fully control the actuator access rules.
如果您希望配置 HTTP 端点的自定义安全性(例如,只允许具有特定角色的用户访问它们),Spring Boot 提供了一些便捷的“@31”对象,可以将其与 Spring 安全性结合使用。
If you wish to configure custom security for HTTP endpoints (for example, to allow only users with a certain role to access them), Spring Boot provides some convenient RequestMatcher
objects that you can use in combination with Spring Security.
典型的 Spring 安全配置可能如下例所示:
A typical Spring Security configuration might look something like the following example:
前一个示例使用“@32”匹配对任何端点的请求,然后确保所有端点都具有“@33”角色。在“@34”上还有其他一些匹配器方法可用。有关详细信息,请参见“@35”。
The preceding example uses EndpointRequest.toAnyEndpoint()
to match a request to any endpoint and then ensures that all have the ENDPOINT_ADMIN
role.
Several other matcher methods are also available on EndpointRequest
.
See the API documentation for details.
如果您在防火墙后面部署应用程序,那么您可能更喜欢在无需身份验证的情况下访问所有致动器端点。您可以通过以下方式来更改“configprop:management.endpoints.web.exposure.include[]”属性:
If you deploy applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. You can do so by changing the configprop:management.endpoints.web.exposure.include[] property, as follows:
management: endpoints: web: exposure: include: "*"
此外,如果存在 Spring Security,你需要添加自定义安全配置,以允许未经身份验证的用户访问端点,如下例所示:
Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints, as the following example shows:
在这两个前面的示例中,配置仅适用于 actuator 端点。由于 Spring Boot 的安全配置在存在任何 bean 的情况下完全退出,因此你需要用适用于应用程序其余部分的规则配置一个额外的 bean。 |
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 |
Cross Site Request Forgery Protection
由于 Spring Boot 依赖于 Spring Security 的默认设置,因此 CSRF 保护默认启用。这意味着,在使用默认安全配置时,需要 @XXX (关闭和记录器端点)、@YYY 或 @ZZZ 的 actuator 端点会收到 403(禁止)错误。
Since Spring Boot relies on Spring Security’s defaults, CSRF protection is turned on by default.
This means that the actuator endpoints that require a POST
(shutdown and loggers endpoints), a PUT
, or a DELETE
get a 403 (forbidden) error when the default security configuration is in use.
我们仅在你创建由非浏览器客户端使用的服务时才建议完全禁用 CSRF 保护。 |
We recommend disabling CSRF protection completely only if you are creating a service that is used by non-browser clients. |
你可以在 Spring Security 参考指南中找到有关 CSRF 保护的更多信息:{url-spring-security-docs}/features/exploits/csrf.html。
You can find additional information about CSRF protection in the {url-spring-security-docs}/features/exploits/csrf.html[Spring Security Reference Guide].
Configuring Endpoints
端点会自动缓存对不采用任何参数的读取操作的响应。若要配置端点缓存响应的时间,请使用其 @PPP 属性。以下示例将 @QQQ 端点的缓存生存时间设置为 10 秒:
Endpoints automatically cache responses to read operations that do not take any parameters.
To configure the amount of time for which an endpoint caches a response, use its cache.time-to-live
property.
The following example sets the time-to-live of the beans
endpoint’s cache to 10 seconds:
management: endpoint: beans: cache: time-to-live: "10s"
@RRR 前缀唯一标识要配置的端点。 |
The |
Sanitize Sensitive Values
@SSS、@TTT 和 @UUU 端点返回的信息可能很敏感,因此默认情况下,这些值总会被完全清理(替换为 @VVV)。
Information returned by the /env
, /configprops
and /quartz
endpoints can be sensitive, so by default values are always fully sanitized (replaced by ).
只有在以下情况下才能以未经清理的形式查看值:
Values can only be viewed in an unsanitized form when:
-
The
show-values
property has been set to something other thanNEVER
-
No custom
SanitizingFunction
beans apply
可以为可清理端点配置 @ZZZ 属性,将其设为以下值之一:
The show-values
property can be configured for sanitizable endpoints to one of the following values:
-
NEVER
- values are always fully sanitized (replaced by)
-
ALWAYS
- values are shown to all users (as long as noSanitizingFunction
bean applies) -
WHEN_AUTHORIZED
- values are shown only to authorized users (as long as noSanitizingFunction
bean applies)
对于 HTTP 端点,如果用户经过身份验证并具有由端点的角色属性配置的角色权限,则该用户会被视为已授权。默认情况下,任何经过身份验证的用户都获得授权。
For HTTP endpoints, a user is considered to be authorized if they have authenticated and have the roles configured by the endpoint’s roles property. By default, any authenticated user is authorized.
对于 JMX 端点,所有用户始终获得授权。
For JMX endpoints, all users are always authorized.
以下示例允许具有 @GGG 角色的所有用户以原始形式查看来自 @HHH 端点的值。未经授权的用户或不具备 @III 角色的用户,只能看到已清理的值。
The following example allows all users with the admin
role to view values from the /env
endpoint in their original form.
Unauthorized users, or users without the admin
role, will see only sanitized values.
management: endpoint: env: show-values: WHEN_AUTHORIZED roles: "admin"
此示例假设未定义任何 |
This example assumes that no |
Hypermedia for Actuator Web Endpoints
通过链接到所有端点添加了一个 “discovery page”。“discovery page” 默认情况下在 /actuator
中提供。
A “discovery page” is added with links to all the endpoints.
The “discovery page” is available on /actuator
by default.
要禁用 “discovery page”,将以下属性添加到应用程序属性中:
To disable the “discovery page”, add the following property to your application properties:
management: endpoints: web: discovery: enabled: false
配置自定义管理上下文路径后,“discovery page” 会自动从 /actuator
移动到管理上下文的根目录。例如,如果管理上下文路径为 /management
,则可以通过 /management
访问发现页面。当管理上下文路径设置为 /
时,将禁用发现页面,以防止发生与其他映射冲突的可能性。
When a custom management context path is configured, the “discovery page” automatically moves from /actuator
to the root of the management context.
For example, if the management context path is /management
, the discovery page is available from /management
.
When the management context path is set to /
, the discovery page is disabled to prevent the possibility of a clash with other mappings.
CORS Support
Cross-origin resource sharing (CORS) 是一种 W3C specification,允许您灵活指定允许哪种跨域请求类型。如果您使用 Spring MVC 或 Spring WebFlux,则可以配置 Actuator 的 Web 端点来支持此类情况。
Cross-origin resource sharing (CORS) is a W3C specification that lets you specify in a flexible way what kind of cross-domain requests are authorized. If you use Spring MVC or Spring WebFlux, you can configure Actuator’s web endpoints to support such scenarios.
CORS 支持默认禁用,仅在您设置 configprop:management.endpoints.web.cors.allowed-origins[] 属性后才会启用。以下配置允许来自 example.com
域的 GET
和 POST
调用:
CORS support is disabled by default and is only enabled once you have set the configprop:management.endpoints.web.cors.allowed-origins[] property.
The following configuration permits GET
and POST
calls from the example.com
domain:
management: endpoints: web: cors: allowed-origins: "https://example.com" allowed-methods: "GET,POST"
请参见 {code-spring-boot-actuator-autoconfigure-src}/endpoint/web/CorsEndpointProperties.java[ |
See {code-spring-boot-actuator-autoconfigure-src}/endpoint/web/CorsEndpointProperties.java[ |
Implementing Custom Endpoints
如果您添加了带 @Endpoint
注释的 @Bean
,则带 @ReadOperation
、@WriteOperation
或 @DeleteOperation
注释的任何方法都会自动通过 JMX 公开,并且在 Web 应用程序中也会通过 HTTP 公开。端点可以使用 Jersey、Spring MVC 或 Spring WebFlux 通过 HTTP 公开。如果 Jersey 和 Spring MVC 都可用,则使用 Spring MVC。
If you add a @Bean
annotated with @Endpoint
, any methods annotated with @ReadOperation
, @WriteOperation
, or @DeleteOperation
are automatically exposed over JMX and, in a web application, over HTTP as well.
Endpoints can be exposed over HTTP by using Jersey, Spring MVC, or Spring WebFlux.
If both Jersey and Spring MVC are available, Spring MVC is used.
以下示例公开了一个读取操作,其返回一个自定义对象:
The following example exposes a read operation that returns a custom object:
您还可以使用 @JmxEndpoint
或 @WebEndpoint
编写特定于技术的端点。这些端点仅限于它们各自的技术。例如,@WebEndpoint
仅通过 HTTP 公开,而不会通过 JMX 公开。
You can also write technology-specific endpoints by using @JmxEndpoint
or @WebEndpoint
.
These endpoints are restricted to their respective technologies.
For example, @WebEndpoint
is exposed only over HTTP and not over JMX.
您可以使用 @EndpointWebExtension
和 @EndpointJmxExtension
编写特定于技术的扩展。这些注释允许您提供特定于技术的操作来增强现有端点。
You can write technology-specific extensions by using @EndpointWebExtension
and @EndpointJmxExtension
.
These annotations let you provide technology-specific operations to augment an existing endpoint.
最后,如果您需要访问特定于 Web 框架的功能,您可以实现 servlet 或者 Spring @Controller
和 @RestController
端点,其缺点是它们无法通过 JMX 访问,或者在使用不同的 Web 框架时无法访问。
Finally, if you need access to web-framework-specific functionality, you can implement servlet or Spring @Controller
and @RestController
endpoints at the cost of them not being available over JMX or when using a different web framework.
Receiving Input
端点上的操作通过其参数接收输入。当通过 Web 公开时,这些参数的值取自 URL 的查询参数和 JSON 请求正文。当通过 JMX 公开时,参数映射到 MBean 的操作参数。默认情况下,参数是必需的。通过使用 @javax.annotation.Nullable
或 @org.springframework.lang.Nullable
注释它们,可以使它们变为可选的。
Operations on an endpoint receive input through their parameters.
When exposed over the web, the values for these parameters are taken from the URL’s query parameters and from the JSON request body.
When exposed over JMX, the parameters are mapped to the parameters of the MBean’s operations.
Parameters are required by default.
They can be made optional by annotating them with either @javax.annotation.Nullable
or @org.springframework.lang.Nullable
.
您可以将 JSON 请求正文中的每个根属性映射到端点的参数。请考虑以下 JSON 请求正文:
You can map each root property in the JSON request body to a parameter of the endpoint. Consider the following JSON request body:
{
"name": "test",
"counter": 42
}
您可以使用此文档调用一个写入操作,它采用 String name
和 int counter
参数,如下例所示:
You can use this to invoke a write operation that takes String name
and int counter
parameters, as the following example shows:
由于端点与技术无关,因此仅能指定简单类型作为方法签名。特别是,不支持声明具有一个参数(其 |
Because endpoints are technology agnostic, only simple types can be specified in the method signature.
In particular, declaring a single parameter with a |
为了让输入映射到操作方法的参数,实现端点的 Java 代码应使用 |
To let the input be mapped to the operation method’s parameters, Java code that implements an endpoint should be compiled with |
Input Type Conversion
如果需要,传递到端点操作方法的参数会自动转换为必需类型。在调用操作方法之前,使用 ApplicationConversionService
的实例,以及使用 @EndpointConverter
限定的任何 Converter
或 GenericConverter
Bean,将通过 JMX 或 HTTP 收到的输入转换为必需类型。
The parameters passed to endpoint operation methods are, if necessary, automatically converted to the required type.
Before calling an operation method, the input received over JMX or HTTP is converted to the required types by using an instance of ApplicationConversionService
as well as any Converter
or GenericConverter
beans qualified with @EndpointConverter
.
Custom Web Endpoints
对 @Endpoint
、@WebEndpoint
或 @EndpointWebExtension
的操作会自动通过 Jersey、Spring MVC 或 Spring WebFlux 暴露到 HTTP 中。如果 Jersey 和 Spring MVC 都可用,则使用 Spring MVC。
Operations on an @Endpoint
, @WebEndpoint
, or @EndpointWebExtension
are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux.
If both Jersey and Spring MVC are available, Spring MVC is used.
Web Endpoint Request Predicates
会自动为在公开在 Web 上的端点上的每个操作生成请求谓词。
A request predicate is automatically generated for each operation on a web-exposed endpoint.
Path
谓词的路径由端点的 ID 和公开在 Web 上的端点的基本路径决定。默认基本路径是 /actuator
。例如,具有 ID 为 sessions
的端点使用 /actuator/sessions
作为其在谓词中的路径。
The path of the predicate is determined by the ID of the endpoint and the base path of the web-exposed endpoints.
The default base path is /actuator
.
For example, an endpoint with an ID of sessions
uses /actuator/sessions
as its path in the predicate.
可以通过使用 @Selector
对操作方法的一个或多个参数进行注释来进一步自定义路径。这样的参数作为路径变量添加到路径谓词中。在调用端点操作时,变量的值会传递到操作方法中。如果你想捕获所有剩余路径元素,则可以将 @Selector(Match=ALL_REMAINING)
添加到最后一个参数,并使其成为与 String[]
转换兼容的类型。
You can further customize the path by annotating one or more parameters of the operation method with @Selector
.
Such a parameter is added to the path predicate as a path variable.
The variable’s value is passed into the operation method when the endpoint operation is invoked.
If you want to capture all remaining path elements, you can add @Selector(Match=ALL_REMAINING)
to the last parameter and make it a type that is conversion-compatible with a String[]
.
HTTP method
谓词的 HTTP 方法由操作类型决定,如下表所示:
The HTTP method of the predicate is determined by the operation type, as shown in the following table:
Operation | HTTP method |
---|---|
|
|
|
|
|
|
Consumes
对于使用请求正文的 @WriteOperation
(HTTP POST
),谓词的 consumes
条款是 application/vnd.spring-boot.actuator.v2+json, application/json
。对于所有其他操作,consumes
条款为空。
For a @WriteOperation
(HTTP POST
) that uses the request body, the consumes
clause of the predicate is application/vnd.spring-boot.actuator.v2+json, application/json
.
For all other operations, the consumes
clause is empty.
Produces
谓词的 produces
条款可以通过 @DeleteOperation
、@ReadOperation
和 @WriteOperation
注释的 produces
属性来确定。该属性是可选的。如果未使用,则 produces
条款会自动确定。
The produces
clause of the predicate can be determined by the produces
attribute of the @DeleteOperation
, @ReadOperation
, and @WriteOperation
annotations.
The attribute is optional.
If it is not used, the produces
clause is determined automatically.
如果操作方法返回 void
或 Void
,则 produces
条款为空。如果操作方法返回 org.springframework.core.io.Resource
,则 produces
条款是 application/octet-stream
。对于所有其他操作,produces
条款是 application/vnd.spring-boot.actuator.v2+json, application/json
。
If the operation method returns void
or Void
, the produces
clause is empty.
If the operation method returns a org.springframework.core.io.Resource
, the produces
clause is application/octet-stream
.
For all other operations, the produces
clause is application/vnd.spring-boot.actuator.v2+json, application/json
.
Web Endpoint Response Status
端点操作的默认响应状态取决于操作类型(读取、写入或删除)以及操作返回内容(如果有)。
The default response status for an endpoint operation depends on the operation type (read, write, or delete) and what, if anything, the operation returns.
如果 @ReadOperation
返回一个值,则响应状态将是 200(确定)。如果它没有返回值,则响应状态将是 404(找不到)。
If a @ReadOperation
returns a value, the response status will be 200 (OK).
If it does not return a value, the response status will be 404 (Not Found).
如果 @WriteOperation
或 @DeleteOperation
返回一个值,则响应状态将是 200(确定)。如果它没有返回值,则响应状态将是 204(无内容)。
If a @WriteOperation
or @DeleteOperation
returns a value, the response status will be 200 (OK).
If it does not return a value, the response status will be 204 (No Content).
如果在没有必需参数或参数无法转换到必需类型的情况下调用了操作,则不会调用操作方法,并且响应状态将是 400(错误的请求)。
If an operation is invoked without a required parameter or with a parameter that cannot be converted to the required type, the operation method is not called, and the response status will be 400 (Bad Request).
Web Endpoint Range Requests
你可以使用 HTTP 范围请求来请求 HTTP 资源的一部分。在使用 Spring MVC 或 Spring Web Flux 时,返回 org.springframework.core.io.Resource
的操作会自动支持范围请求。
You can use an HTTP range request to request part of an HTTP resource.
When using Spring MVC or Spring Web Flux, operations that return a org.springframework.core.io.Resource
automatically support range requests.
在使用 Jersey 时不支持范围请求。 |
Range requests are not supported when using Jersey. |
Web Endpoint Security
对 Web 端点或特定 Web 端点的扩展上执行的操作可以将当前 java.security.Principal
或 org.springframework.boot.actuate.endpoint.SecurityContext
接收为方法参数。前者通常与 @Nullable
结合使用,以便为已认证和未认证用户提供不同的行为。后者通常用来通过使用其 isUserInRole(String)
方法来执行授权检查。
An operation on a web endpoint or a web-specific endpoint extension can receive the current java.security.Principal
or org.springframework.boot.actuate.endpoint.SecurityContext
as a method parameter.
The former is typically used in conjunction with @Nullable
to provide different behavior for authenticated and unauthenticated users.
The latter is typically used to perform authorization checks by using its isUserInRole(String)
method.
Servlet Endpoints
可以通过实现同时实现 Supplier<EndpointServlet>
的使用 @ServletEndpoint
注释的类来将 Servlet 公开为端点。Servlet 端点提供与 Servlet 容器的更深入集成,但也以牺牲可移植性为代价。它们旨在用于将现有 Servlet 公开为端点。对于新端点,应尽可能选择 @Endpoint
和 @WebEndpoint
注释。
A servlet can be exposed as an endpoint by implementing a class annotated with @ServletEndpoint
that also implements Supplier<EndpointServlet>
.
Servlet endpoints provide deeper integration with the servlet container but at the expense of portability.
They are intended to be used to expose an existing servlet as an endpoint.
For new endpoints, the @Endpoint
and @WebEndpoint
annotations should be preferred whenever possible.
Controller Endpoints
可以使用 @ControllerEndpoint
和 @RestControllerEndpoint
来实现仅通过 Spring MVC 或 Spring WebFlux 公开的端点。方法是使用适用于 Spring MVC 和 Spring WebFlux 的标准注释(例如 @RequestMapping
和 @GetMapping
)映射,端点的 ID 作为该路径的前缀。控制器端点提供与 Spring 的 Web 框架的更深入集成,但也以牺牲可移植性为代价。应尽可能选择 @Endpoint
和 @WebEndpoint
注释。
You can use @ControllerEndpoint
and @RestControllerEndpoint
to implement an endpoint that is exposed only by Spring MVC or Spring WebFlux.
Methods are mapped by using the standard annotations for Spring MVC and Spring WebFlux, such as @RequestMapping
and @GetMapping
, with the endpoint’s ID being used as a prefix for the path.
Controller endpoints provide deeper integration with Spring’s web frameworks but at the expense of portability.
The @Endpoint
and @WebEndpoint
annotations should be preferred whenever possible.
Health Information
你可以使用健康信息来检查正在运行的应用程序的状态。它经常由监控软件使用,以便在生产系统出现故障时提醒某人。由 health
端点公开的信息取决于 configprop:management.endpoint.health.show-details[] 和 configprop:management.endpoint.health.show-components[] 属性,它们可以配置为以下值之一:
You can use health information to check the status of your running application.
It is often used by monitoring software to alert someone when a production system goes down.
The information exposed by the health
endpoint depends on the configprop:management.endpoint.health.show-details[] and configprop:management.endpoint.health.show-components[] properties, which can be configured with one of the following values:
Name | Description |
---|---|
|
Details are never shown. |
|
Details are shown only to authorized users.
Authorized roles can be configured by using |
|
Details are shown to all users. |
默认值是 never
。当用户属于端点的某个角色或多个角色时,被视为已授权。如果端点没有配置角色(这是默认值),则所有已验证用户都视为已授权。你可以使用 configprop: management. endpoint.health.roles[] 属性来配置角色。
The default value is never
.
A user is considered to be authorized when they are in one or more of the endpoint’s roles.
If the endpoint has no configured roles (the default), all authenticated users are considered to be authorized.
You can configure the roles by using the configprop:management.endpoint.health.roles[] property.
如果你已经保护了应用程序并希望使用 |
If you have secured your application and wish to use |
运行状况信息从 {code-spring-boot-actuator-src}/health/HealthContributorRegistry.java[HealthContributorRegistry
](默认情况下,所有在你的 ApplicationContext
中定义的 {code-spring-boot-actuator-src}/health/HealthContributor.java[HealthContributor
] 实例)的内容中收集。Spring Boot 包含众多自动配置的 HealthContributors
,你也可以编写你自己的 HealthContributors
。
Health information is collected from the content of a {code-spring-boot-actuator-src}/health/HealthContributorRegistry.java[HealthContributorRegistry
] (by default, all {code-spring-boot-actuator-src}/health/HealthContributor.java[HealthContributor
] instances defined in your ApplicationContext
).
Spring Boot includes a number of auto-configured HealthContributors
, and you can also write your own.
HealthContributor
可以是 HealthIndicator
或 CompositeHealthContributor
。HealthIndicator
提供实际的运行状况信息,包括 Status
。CompositeHealthContributor
提供其他 HealthContributors
的混合。贡献者共同形成树结构来代表整个系统的运行状况。
A HealthContributor
can be either a HealthIndicator
or a CompositeHealthContributor
.
A HealthIndicator
provides actual health information, including a Status
.
A CompositeHealthContributor
provides a composite of other HealthContributors
.
Taken together, contributors form a tree structure to represent the overall system health.
默认情况下,最终系统运行状况是由 StatusAggregator`派生的,该 `StatusAggregator
根据已排序的状态列表对来自每个 HealthIndicator
的状态进行分类。分类列表中的第一个状态用作整体运行状况状态。如果没有任何 HealthIndicator
返回 StatusAggregator
已知的状态,则使用 UNKNOWN
状态。
By default, the final system health is derived by a StatusAggregator
, which sorts the statuses from each HealthIndicator
based on an ordered list of statuses.
The first status in the sorted list is used as the overall health status.
If no HealthIndicator
returns a status that is known to the StatusAggregator
, an UNKNOWN
status is used.
你可以使用 |
You can use the |
Auto-configured HealthIndicators
如合适,Spring Boot 会自动配置下表中列出的 HealthIndicators
。你还可以通过使用下表中列出的 key
配置 management.health.key.enabled
,从而启用或禁用选定的指标:
When appropriate, Spring Boot auto-configures the HealthIndicators
listed in the following table.
You can also enable or disable selected indicators by configuring management.health.key.enabled
,
with the key
listed in the following table:
Key | Name | Description |
---|---|---|
|
{code-spring-boot-actuator-src}/cassandra/CassandraDriverHealthIndicator.java[ |
Checks that a Cassandra database is up. |
|
{code-spring-boot-actuator-src}/couchbase/CouchbaseHealthIndicator.java[ |
Checks that a Couchbase cluster is up. |
|
{code-spring-boot-actuator-src}/jdbc/DataSourceHealthIndicator.java[ |
Checks that a connection to |
|
{code-spring-boot-actuator-src}/system/DiskSpaceHealthIndicator.java[ |
Checks for low disk space. |
|
{code-spring-boot-actuator-src}/elasticsearch/ElasticsearchRestClientHealthIndicator.java[ |
Checks that an Elasticsearch cluster is up. |
|
{code-spring-boot-actuator-src}/hazelcast/HazelcastHealthIndicator.java[ |
Checks that a Hazelcast server is up. |
|
{code-spring-boot-actuator-src}/influx/InfluxDbHealthIndicator.java[ |
Checks that an InfluxDB server is up. |
|
{code-spring-boot-actuator-src}/jms/JmsHealthIndicator.java[ |
Checks that a JMS broker is up. |
|
{code-spring-boot-actuator-src}/ldap/LdapHealthIndicator.java[ |
Checks that an LDAP server is up. |
|
{code-spring-boot-actuator-src}/mail/MailHealthIndicator.java[ |
Checks that a mail server is up. |
|
{code-spring-boot-actuator-src}/data/mongo/MongoHealthIndicator.java[ |
Checks that a Mongo database is up. |
|
{code-spring-boot-actuator-src}/neo4j/Neo4jHealthIndicator.java[ |
Checks that a Neo4j database is up. |
|
{code-spring-boot-actuator-src}/health/PingHealthIndicator.java[ |
Always responds with |
|
{code-spring-boot-actuator-src}/amqp/RabbitHealthIndicator.java[ |
Checks that a Rabbit server is up. |
|
{code-spring-boot-actuator-src}/data/redis/RedisHealthIndicator.java[ |
Checks that a Redis server is up. |
可以通过设置 configprop:management.health.defaults.enabled[] 属性来禁用它们。 |
You can disable them all by setting the configprop:management.health.defaults.enabled[] property. |
其他 HealthIndicators
是可用的,但默认情况下未启用:
Additional HealthIndicators
are available but are not enabled by default:
Key | Name | Description |
---|---|---|
|
{code-spring-boot-actuator-src}/availability/LivenessStateHealthIndicator.java[ |
Exposes the “Liveness” application availability state. |
|
{code-spring-boot-actuator-src}/availability/ReadinessStateHealthIndicator.java[ |
Exposes the “Readiness” application availability state. |
Writing Custom HealthIndicators
要提供自定义健康信息,可以注册实现 {code-spring-boot-actuator-src}/health/HealthIndicator.java[HealthIndicator
] 接口的 Spring bean。您需要提供 health()
方法的实现并返回 Health
响应。Health
响应应包括一个状态,并且可以包含可选的要显示的附加详细信息。以下代码显示一个 HealthIndicator
实现示例:
To provide custom health information, you can register Spring beans that implement the {code-spring-boot-actuator-src}/health/HealthIndicator.java[HealthIndicator
] interface.
You need to provide an implementation of the health()
method and return a Health
response.
The Health
response should include a status and can optionally include additional details to be displayed.
The following code shows a sample HealthIndicator
implementation:
给定 |
The identifier for a given |
健康指示器通常通过 HTTP 调用,并且需要在任何连接超时之前做出响应。Spring Boot 会针对任何响应时间超过 10 秒的健康指示器记录警告消息。如果要配置此阀值,可以使用 configprop:management.endpoint.health.logging.slow-indicator-threshold[] 属性。 |
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 configprop:management.endpoint.health.logging.slow-indicator-threshold[] property. |
除了 Spring Boot 预定义的 {code-spring-boot-actuator-src}/health/Status.java[Status
] 类型,Health
还可以返回表示新系统状态的自定义 Status
。在这种情况下,还需要提供 {code-spring-boot-actuator-src}/health/StatusAggregator.java[StatusAggregator
] 接口的自定义实现,或者必须使用 configprop:management.endpoint.health.status.order[] 配置属性来配置默认实现。
In addition to Spring Boot’s predefined {code-spring-boot-actuator-src}/health/Status.java[Status
] types, Health
can return a custom Status
that represents a new system state.
In such cases, you also need to provide a custom implementation of the {code-spring-boot-actuator-src}/health/StatusAggregator.java[StatusAggregator
] interface, or you must configure the default implementation by using the configprop:management.endpoint.health.status.order[] configuration property.
例如,假设一个新的 Status
在您的其中一个 HealthIndicator
实现中使用,其代码为 FATAL
。要配置严重性顺序,请将以下属性添加到您的应用程序属性:
For example, assume a new Status
with a code of FATAL
is being used in one of your HealthIndicator
implementations.
To configure the severity order, add the following property to your application properties:
management: endpoint: health: status: order: "fatal,down,out-of-service,unknown,up"
响应中的 HTTP 状态代码反映了整体健康状况。默认情况下,OUT_OF_SERVICE
和 DOWN
映射到 503。任何未映射的健康状态,包括 UP
,都映射到 200。您可能还想通过 HTTP 访问健康端点时注册自定义状态映射。配置自定义映射会禁用 DOWN
和 OUT_OF_SERVICE
的默认映射。要保留默认映射,必须显式配置它们,以及任何自定义映射。例如,以下属性将 FATAL
映射到 503(服务不可用),并保留 DOWN
和 OUT_OF_SERVICE
的默认映射:
The HTTP status code in the response reflects the overall health status.
By default, OUT_OF_SERVICE
and DOWN
map to 503.
Any unmapped health statuses, including UP
, map to 200.
You might also want to register custom status mappings if you access the health endpoint over HTTP.
Configuring a custom mapping disables the defaults mappings for DOWN
and OUT_OF_SERVICE
.
If you want to retain the default mappings, you must explicitly configure them, alongside any custom mappings.
For example, the following property maps FATAL
to 503 (service unavailable) and retains the default mappings for DOWN
and OUT_OF_SERVICE
:
management: endpoint: health: status: http-mapping: down: 503 fatal: 503 out-of-service: 503
如果您需要更多控制,可以定义自己的 |
If you need more control, you can define your own |
下表显示了内置状态的默认状态映射:
The following table shows the default status mappings for the built-in statuses:
Status | Mapping |
---|---|
|
|
|
|
|
No mapping by default, so HTTP status is |
|
No mapping by default, so HTTP status is |
Reactive Health Indicators
对于响应应用程序,例如使用 Spring WebFlux 的应用程序,ReactiveHealthContributor
提供了一个非阻塞合约来获取应用程序的健康状况。类似于传统 HealthContributor
,健康信息是从 {code-spring-boot-actuator-src}/health/ReactiveHealthContributorRegistry.java[ReactiveHealthContributorRegistry
] (默认情况下,所有 {code-spring-boot-actuator-src}/health/HealthContributor.java[HealthContributor
] 和 {code-spring-boot-actuator-src}/health/ReactiveHealthContributor.java[ReactiveHealthContributor
] 实例均在您的 ApplicationContext
中定义)的内容中收集的。针对非响应式 API 进行检查的常规 HealthContributors
在弹性调度程序上执行。
For reactive applications, such as those that use Spring WebFlux, ReactiveHealthContributor
provides a non-blocking contract for getting application health.
Similar to a traditional HealthContributor
, health information is collected from the content of a {code-spring-boot-actuator-src}/health/ReactiveHealthContributorRegistry.java[ReactiveHealthContributorRegistry
] (by default, all {code-spring-boot-actuator-src}/health/HealthContributor.java[HealthContributor
] and {code-spring-boot-actuator-src}/health/ReactiveHealthContributor.java[ReactiveHealthContributor
] instances defined in your ApplicationContext
).
Regular HealthContributors
that do not check against a reactive API are executed on the elastic scheduler.
在反应式应用程序中,你应该使用 |
In a reactive application, you should use the |
要从反应式 API 提供自定义健康信息,你可以注册实现 {code-spring-boot-actuator-src}/health/ReactiveHealthIndicator.java[ReactiveHealthIndicator
] 接口的 Spring bean。下面的代码展示了一个示例 ReactiveHealthIndicator
实现:
To provide custom health information from a reactive API, you can register Spring beans that implement the {code-spring-boot-actuator-src}/health/ReactiveHealthIndicator.java[ReactiveHealthIndicator
] interface.
The following code shows a sample ReactiveHealthIndicator
implementation:
为了自动处理错误,考虑从 |
To handle the error automatically, consider extending from |
Auto-configured ReactiveHealthIndicators
当合适时,Spring Boot 会自动配置以下 ReactiveHealthIndicators
:
When appropriate, Spring Boot auto-configures the following ReactiveHealthIndicators
:
Key | Name | Description |
---|---|---|
|
{code-spring-boot-actuator-src}/cassandra/CassandraDriverReactiveHealthIndicator.java[ |
Checks that a Cassandra database is up. |
|
{code-spring-boot-actuator-src}/couchbase/CouchbaseReactiveHealthIndicator.java[ |
Checks that a Couchbase cluster is up. |
|
{code-spring-boot-actuator-src}/data/elasticsearch/ElasticsearchReactiveHealthIndicator.java[ |
Checks that an Elasticsearch cluster is up. |
|
{code-spring-boot-actuator-src}/data/mongo/MongoReactiveHealthIndicator.java[ |
Checks that a Mongo database is up. |
|
{code-spring-boot-actuator-src}/neo4j/Neo4jReactiveHealthIndicator.java[ |
Checks that a Neo4j database is up. |
|
{code-spring-boot-actuator-src}/data/redis/RedisReactiveHealthIndicator.java[ |
Checks that a Redis server is up. |
在必要时,反应式指标会替换常规指标。此外,任何没有明确处理的 |
If necessary, reactive indicators replace the regular ones.
Also, any |
Health Groups
有时候,将健康指标整理成可用于不同用途的分组很有用。
It is sometimes useful to organize health indicators into groups that you can use for different purposes.
要创建一个健康指标分组,你可以使用 management.endpoint.health.group.<name>
属性,并为 include
或 exclude
指定一个健康指标 ID 列表。例如,为了创建一个仅包含数据库指标的分组,你可以定义以下内容:
To create a health indicator group, you can use the management.endpoint.health.group.<name>
property and specify a list of health indicator IDs to include
or exclude
.
For example, to create a group that includes only database indicators you can define the following:
management: endpoint: health: group: custom: include: "db"
然后,你可以通过点击 http://localhost:8080/actuator/health/custom
来查看结果。
You can then check the result by hitting http://localhost:8080/actuator/health/custom
.
类似地,为了创建一个将数据库指标从分组中排除、同时包含所有其他指标的分组,你可以定义以下内容:
Similarly, to create a group that excludes the database indicators from the group and includes all the other indicators, you can define the following:
management: endpoint: health: group: custom: exclude: "db"
默认情况下,如果一个健康分组包含或排除了不存在的健康指标,启动将会失败。要禁用此行为,将 configprop:management.endpoint.health.validate-group-membership[] 设置为 false
。
By default, startup will fail if a health group includes or excludes a health indicator that does not exist.
To disable this behavior set configprop:management.endpoint.health.validate-group-membership[] to false
.
默认情况下,组会继承与系统健康相同的 StatusAggregator
和 HttpCodeStatusMapper
设置。不过,你也可以在组级别上定义这些设置。你还可以根据需要覆盖 show-details
和 roles
属性:
By default, groups inherit the same StatusAggregator
and HttpCodeStatusMapper
settings as the system health.
However, you can also define these on a per-group basis.
You can also override the show-details
and roles
properties if required:
management: endpoint: health: group: custom: show-details: "when-authorized" roles: "admin" status: order: "fatal,up" http-mapping: fatal: 500 out-of-service: 500
如果你需要为分组注册自定义 |
You can use |
一个健康分组还可以包含/排除一个 CompositeHealthContributor
。你还可以仅包含/排除 CompositeHealthContributor
的某个组件。这可以通过使用组件的全限定名称来实现,如下所示:
A health group can also include/exclude a CompositeHealthContributor
.
You can also include/exclude only a certain component of a CompositeHealthContributor
.
This can be done using the fully qualified name of the component as follows:
management.endpoint.health.group.custom.include="test/primary"
management.endpoint.health.group.custom.exclude="test/primary/b"
在上述示例中,custom
分组将包含名称为 primary
的 HealthContributor
,它是一个复合 test
的组件。这里,primary
本身是一个复合体,并且名称为 b
的 HealthContributor
将从 custom
组中排除。
In the example above, the custom
group will include the HealthContributor
with the name primary
which is a component of the composite test
.
Here, primary
itself is a composite and the HealthContributor
with the name b
will be excluded from the custom
group.
健康组可以使用主端口或管理端口上的额外路径。这在云环境中很有用,例如 Kubernetes,其中出于安全目的,通常为执行器端点使用单独的管理端口。由于主应用程序即使健康检查成功,也可能无法正常工作,拥有一个单独的端口可能会导致不可靠的健康检查。健康组可以通过以下方式配置额外路径:
Health groups can be made available at an additional path on either the main or management port. This is useful in cloud environments such as Kubernetes, where it is quite common to use a separate management port for the actuator endpoints for security purposes. Having a separate port could lead to unreliable health checks because the main application might not work properly even if the health check is successful. The health group can be configured with an additional path as follows:
management.endpoint.health.group.live.additional-path="server:/healthz"
这将使 live
健康组在 /healthz
处的主服务器端口上可用。前缀是必需的,它必须是 server:
(代表主服务器端口)或 management:
(代表管理端口(如果已配置))中的一个。路径必须是一个单一的路径部分。
This would make the live
health group available on the main server port at /healthz
.
The prefix is mandatory and must be either server:
(represents the main server port) or management:
(represents the management port, if configured.)
The path must be a single path segment.
DataSource Health
DataSource
健康指标展示了标准数据源和路由数据源 bean 的运行状况。路由数据源的运行状况包括其每个目标数据源的运行状况。在健康端点的响应中,每个路由数据源的目标都通过使用其路由键来命名。如果你不希望在指标输出中包含路由数据源,请将 configprop:management.health.db.ignore-routing-data-sources[] 设置为 true
。
The DataSource
health indicator shows the health of both standard data sources and routing data source beans.
The health of a routing data source includes the health of each of its target data sources.
In the health endpoint’s response, each of a routing data source’s targets is named by using its routing key.
If you prefer not to include routing data sources in the indicator’s output, set configprop:management.health.db.ignore-routing-data-sources[] to true
.
Kubernetes Probes
部署在 Kubernetes 上的应用程序可以使用 Container Probes 提供其内部状态的信息。根据 your Kubernetes configuration,kubelet 会调用那些探测并对结果做出反应。
Applications deployed on Kubernetes can provide information about their internal state with Container Probes. Depending on your Kubernetes configuration, the kubelet calls those probes and reacts to the result.
默认情况下,Spring Boot 会管理你的 Application Availability State。如果部署在 Kubernetes 环境中,执行器会从 ApplicationAvailability
接口中收集 “Liveness” 和 “Readiness” 信息,然后使用这些信息在专用 health indicators 中: LivenessStateHealthIndicator
和 ReadinessStateHealthIndicator
。这些指标显示在全局健康端点 ("/actuator/health"
) 上。它们还通过使用 health groups: "/actuator/health/liveness"
和 "/actuator/health/readiness"
公开为单独的 HTTP 探测。
By default, Spring Boot manages your Application Availability State.
If deployed in a Kubernetes environment, actuator gathers the “Liveness” and “Readiness” information from the ApplicationAvailability
interface and uses that information in dedicated health indicators: LivenessStateHealthIndicator
and ReadinessStateHealthIndicator
.
These indicators are shown on the global health endpoint ("/actuator/health"
).
They are also exposed as separate HTTP Probes by using health groups: "/actuator/health/liveness"
and "/actuator/health/readiness"
.
然后,你可以使用以下端点信息配置你的 Kubernetes 基础设施:
You can then configure your Kubernetes infrastructure with the following endpoint information:
livenessProbe:
httpGet:
path: "/actuator/health/liveness"
port: <actuator-port>
failureThreshold: ...
periodSeconds: ...
readinessProbe:
httpGet:
path: "/actuator/health/readiness"
port: <actuator-port>
failureThreshold: ...
periodSeconds: ...
|
|
这些健康组仅在你应用程序 runs in a Kubernetes environment 时才会自动启用。你可以通过使用 configprop:management.endpoint.health.probes.enabled[] 配置属性在任何环境中启用它们。
These health groups are automatically enabled only if the application runs in a Kubernetes environment. You can enable them in any environment by using the configprop:management.endpoint.health.probes.enabled[] configuration property.
如果应用程序启动的时间比配置的活跃时间段长,Kubernetes 会将 |
If an application takes longer to start than the configured liveness period, Kubernetes mentions the |
如果你的执行器端点部署在单独的管理上下文中,则这些端点不会与主应用程序使用相同的 Web 基础设施(端口、连接池、框架组件)。在这种情况下,即使主应用程序无法正常工作(例如,它无法接受新连接),探测检查也可能会成功。因此,最好在主服务器端口上启用 liveness
和 readiness
健康组。这可以通过设置以下属性来完成:
If your Actuator endpoints are deployed on a separate management context, the endpoints do not use the same web infrastructure (port, connection pools, framework components) as the main application.
In this case, a probe check could be successful even if the main application does not work properly (for example, it cannot accept new connections).
For this reason, it is a good idea to make the liveness
and readiness
health groups available on the main server port.
This can be done by setting the following property:
management.endpoint.health.probes.add-additional-paths=true
这将在主服务器端口上将 liveness
组设为可用于 /livez
,将 readiness
组设为可用于 /readyz
。路径可以使用每个组上的 additional-path
属性来自定义,请参阅 health groups 了解详情。
This would make the liveness
group available at /livez
and the readiness
group available at /readyz
on the main server port.
Paths can be customized using the additional-path
property on each group, see health groups for details.
Checking External State With Kubernetes Probes
执行器将 “liveness” 和 “readiness” 探测配置为健康组。这意味着所有的 health groups features 都对它们可用。例如,你可以配置其他健康指标:
Actuator configures the “liveness” and “readiness” probes as Health Groups. This means that all the health groups features are available for them. You can, for example, configure additional Health Indicators:
management: endpoint: health: group: readiness: include: "readinessState,customCheck"
默认情况下,Spring Boot 不会将其他健康指标添加到这些组中。
By default, Spring Boot does not add other health indicators to these groups.
“liveness” 探测不应依赖于外部系统的运行状况检查。如果 liveness state of an application 已中断,Kubernetes 会通过重新启动应用程序实例来尝试解决该问题。这意味着,如果外部系统(例如数据库、Web API 或外部缓存)发生故障,Kubernetes 可能会重新启动所有应用程序实例并创建级联故障。
The “liveness” probe should not depend on health checks for external systems. If the liveness state of an application is broken, Kubernetes tries to solve that problem by restarting the application instance. This means that if an external system (such as a database, a Web API, or an external cache) fails, Kubernetes might restart all application instances and create cascading failures.
至于 “readiness” 探测,检查外部系统的选择必须由应用程序开发人员仔细做出。因此,Spring Boot 不会在准备就绪探测中包括任何其他运行状况检查。如果 readiness state of an application instance 未准备好,Kubernetes 不会将流量路由到该实例。某些外部系统可能不会被应用程序实例共享,在这种情况下,它们可以包含在准备就绪探测中。其他外部系统可能对应用程序不必要(应用程序可能有断路器和后备选项),在这种情况下,绝对不应包含这些外部系统。不幸的是,所有应用程序实例共享的外部系统很常见,你必须做出判断:将其包含在准备就绪探测中并希望在外部服务关闭时将应用程序排除在外或将其排除在外并处理堆栈中更高的故障,也许通过在调用方中使用断路器。
As for the “readiness” probe, the choice of checking external systems must be made carefully by the application developers. For this reason, Spring Boot does not include any additional health checks in the readiness probe. If the readiness state of an application instance is unready, Kubernetes does not route traffic to that instance. Some external systems might not be shared by application instances, in which case they could be included in a readiness probe. Other external systems might not be essential to the application (the application could have circuit breakers and fallbacks), in which case they definitely should not be included. Unfortunately, an external system that is shared by all application instances is common, and you have to make a judgement call: Include it in the readiness probe and expect that the application is taken out of service when the external service is down or leave it out and deal with failures higher up the stack, perhaps by using a circuit breaker in the caller.
如果应用程序的所有实例都未准备就绪,则带 |
If all instances of an application are unready, a Kubernetes Service with |
此外,如果应用程序使用 Kubernetes autoscaling,它对从负载平衡器中移除应用程序的反应可能不同,具体取决于其自动伸缩器配置。
Also, if an application uses Kubernetes autoscaling, it may react differently to applications being taken out of the load-balancer, depending on its autoscaler configuration.
Application Lifecycle and Probe States
Kubernetes 探测支持的一个重要方面是它与应用程序生命周期的协调一致。AvailabilityState
(也就是应用程序的内存内部状态)与实际探测(公开该状态)之间有显着差别。根据应用程序生命周期的阶段,该探测可能不可用。
An important aspect of the Kubernetes Probes support is its consistency with the application lifecycle.
There is a significant difference between the AvailabilityState
(which is the in-memory, internal state of the application)
and the actual probe (which exposes that state).
Depending on the phase of application lifecycle, the probe might not be available.
Spring Boot 会发布 application events during startup and shutdown,并且探测可以监听此类事件并公开 AvailabilityState
信息。
Spring Boot publishes application events during startup and shutdown,
and probes can listen to such events and expose the AvailabilityState
information.
下表显示了 AvailabilityState
和 HTTP 连接器在不同阶段的状态。
The following tables show the AvailabilityState
and the state of HTTP connectors at different stages.
Spring Boot 应用程序启动时:
When a Spring Boot application starts:
Startup phase | LivenessState | ReadinessState | HTTP server | Notes |
---|---|---|---|---|
Starting |
|
|
Not started |
Kubernetes checks the "liveness" Probe and restarts the application if it takes too long. |
Started |
|
|
Refuses requests |
The application context is refreshed. The application performs startup tasks and does not receive traffic yet. |
Ready |
|
|
Accepts requests |
Startup tasks are finished. The application is receiving traffic. |
Spring Boot 应用程序关闭时:
When a Spring Boot application shuts down:
Shutdown phase | Liveness State | Readiness State | HTTP server | Notes |
---|---|---|---|---|
Running |
|
|
Accepts requests |
Shutdown has been requested. |
Graceful shutdown |
|
|
New requests are rejected |
If enabled, graceful shutdown processes in-flight requests. |
Shutdown complete |
N/A |
N/A |
Server is shut down |
The application context is closed and the application is shut down. |
请参阅 Kubernetes container lifecycle section 了解更多有关 Kubernetes 部署的信息。 |
See Kubernetes container lifecycle section for more information about Kubernetes deployment. |
Application Information
应用程序信息公开从所有 {code-spring-boot-actuator-src}/info/InfoContributor.java[InfoContributor
] bean(已在 ApplicationContext
中定义)收集的各种信息。Spring Boot 包含多个自动配置的 InfoContributor
bean,您也可以编写自己的。
Application information exposes various information collected from all {code-spring-boot-actuator-src}/info/InfoContributor.java[InfoContributor
] beans defined in your ApplicationContext
.
Spring Boot includes a number of auto-configured InfoContributor
beans, and you can write your own.
Auto-configured InfoContributors
在适当的时候,Spring 将自动配置以下 InfoContributor
bean:
When appropriate, Spring auto-configures the following InfoContributor
beans:
ID | Name | Description | Prerequisites |
---|---|---|---|
|
{code-spring-boot-actuator-src}/info/BuildInfoContributor.java[ |
Exposes build information. |
A |
|
{code-spring-boot-actuator-src}/info/EnvironmentInfoContributor.java[ |
Exposes any property from the |
None. |
|
{code-spring-boot-actuator-src}/info/GitInfoContributor.java[ |
Exposes git information. |
A |
|
{code-spring-boot-actuator-src}/info/JavaInfoContributor.java[ |
Exposes Java runtime information. |
None. |
|
{code-spring-boot-actuator-src}/info/OsInfoContributor.java[ |
Exposes Operating System information. |
None. |
|
{code-spring-boot-actuator-src}/info/ProcessInfoContributor.java[ |
Exposes process information. |
None. |
单独分发者的启用与否由其 management.info.<id>.enabled
属性控制。不同的分发者对此属性有不同的默认值,具体取决于其前提条件和它们公开信息的性质。
Whether an individual contributor is enabled is controlled by its management.info.<id>.enabled
property.
Different contributors have different defaults for this property, depending on their prerequisites and the nature of the information that they expose.
如果没有前置条件表明应启用它们,env
、java
、os
和 process
分发者默认情况下处于禁用状态。可通过将 management.info.<id>.enabled
属性设置为 true
来启用每个分发者。
With no prerequisites to indicate that they should be enabled, the env
, java
, os
, and process
contributors are disabled by default.
Each can be enabled by setting its management.info.<id>.enabled
property to true
.
build
和 git
信息分发者默认情况下处于启用状态。可通过将 management.info.<id>.enabled
属性设置为 false
来禁用每个分发者。或者,要禁用通常默认启用的所有分发者,将 configprop:management.info.defaults.enabled[] 属性设置为 false
。
The build
and git
info contributors are enabled by default.
Each can be disabled by setting its management.info.<id>.enabled
property to false
.
Alternatively, to disable every contributor that is usually enabled by default, set the configprop:management.info.defaults.enabled[] property to false
.
Custom Application Information
当 env
分发者启用时,您可以通过设置 info.*
Spring 属性来定制 info
终端公开的数据。所有 info
键下的 Environment
属性会自动公开。例如,您可以添加以下设置到 application.properties
文件:
When the env
contributor is enabled, you can customize the data exposed by the info
endpoint by setting info.*
Spring properties.
All Environment
properties under the info
key are automatically exposed.
For example, you could add the following settings to your application.properties
file:
info: app: encoding: "UTF-8" java: source: "17" target: "17"
您可以也 expand info properties at build time 那些值,而不是硬编码。 Rather than hardcoding those values, you could also expand info properties at build time. 假设您使用 Maven,您可以这样重写前一个示例: Assuming you use Maven, you could rewrite the preceding example as follows: info: app: encoding: "@project.build.sourceEncoding@" java: source: "@java.version@" target: "@java.version@" |
Git Commit Information
info
终端的另一个有用的功能是它能发布有关 git
源代码存储库在项目构建时的状态的信息。如果存在 GitProperties
bean,您可以使用 info
终端公开这些属性。
Another useful feature of the info
endpoint is its ability to publish information about the state of your git
source code repository when the project was built.
If a GitProperties
bean is available, you can use the info
endpoint to expose these properties.
如果类路径的根目录中存在 |
A |
默认情况下,此终端公开 git.branch
、git.commit.id
和 git.commit.time
属性(如果存在)。如果您不希望在终端响应中出现任何这些属性,则需要从 git.properties
文件中排除这些属性。如果您想显示全部 git 信息(即 git.properties
的全部内容),请使用 configprop:management.info.git.mode[] 属性,如下所示:
By default, the endpoint exposes git.branch
, git.commit.id
, and git.commit.time
properties, if present.
If you do not want any of these properties in the endpoint response, they need to be excluded from the git.properties
file.
If you want to display the full git information (that is, the full content of git.properties
), use the configprop:management.info.git.mode[] property, as follows:
management: info: git: mode: "full"
要从 info
终端中完全禁用 git 提交信息,请将 configprop:management.info.git.enabled[] 属性设置为 false
,如下所示:
To disable the git commit information from the info
endpoint completely, set the configprop:management.info.git.enabled[] property to false
, as follows:
management: info: git: enabled: false
Build Information
如果 BuildProperties
bean 可用,info
端点还可以发布有关你的构建的信息,只要 classpath 中提供 META-INF/build-info.properties
文件,情况即是如此。
If a BuildProperties
bean is available, the info
endpoint can also publish information about your build.
This happens if a META-INF/build-info.properties
file is available in the classpath.
Maven 和 Gradle 插件均可生成该文件,有关更多详细信息,请参阅“how to generate build information”。 |
The Maven and Gradle plugins can both generate that file. See "how to generate build information" for more details. |
Java Information
info
端点发布有关你的 Java 运行时环境的信息,有关更多详细信息,请参阅 JavaInfo
。
The info
endpoint publishes information about your Java runtime environment, see JavaInfo
for more details.
OS Information
info
端点发布有关你的操作系统的的信息,有关更多详细信息,请参阅 OsInfo
。
The info
endpoint publishes information about your Operating System, see OsInfo
for more details.
Process Information
info
端点发布有关你的进程的信息,有关更多详细信息,请参阅 ProcessInfo
。
The info
endpoint publishes information about your process, see ProcessInfo
for more details.
Writing Custom InfoContributors
若要提供自定义应用程序信息,可以注册实现 {code-spring-boot-actuator-src}/info/InfoContributor.java[InfoContributor
] 界面的 Spring bean。
To provide custom application information, you can register Spring beans that implement the {code-spring-boot-actuator-src}/info/InfoContributor.java[InfoContributor
] interface.
以下示例包含一个具有单个值的 example
条目:
The following example contributes an example
entry with a single value:
如果访问了 info
端点,应该会看到包含以下附加条目的响应:
If you reach the info
endpoint, you should see a response that contains the following additional entry:
{
"example": {
"key" : "value"
}
}