Spring Boot Actuator: Production-ready Features
1. 添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
2. 端点
端点 | 描述 | 默认启用 |
---|---|---|
health | 应用健康状态 | 是 |
info | 应用信息 | 是 |
metrics | 应用度量指标 | 否 |
beans | 显示所有Spring Beans | 否 |
mappings | 显示所有@RequestMapping路径 | 否 |
env | 显示环境变量 | 否 |
shutdown | 优雅关闭应用 | 否 |
2.1. 启用端点
默认情况下,除 之外的所有终结点都处于启用状态。若要配置终结点的启用,请使用其属性。以下示例启用终结点:
management.endpoint.shutdown.enabled=true
如果您希望启用端点是选择加入而不是选择退出,请将属性设置为 ,并使用单个端点属性重新选择加入。以下示例启用端点并禁用所有其他端点:
management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true
2.2. 公开端点
由于端点可能包含敏感信息,因此应仔细考虑何时公开它们。 下表显示了内置终结点的默认公开:
ID | JMX | Web |
---|---|---|
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
Yes |
|
N/A |
No |
|
Yes |
No |
|
Yes |
Yes |
|
Yes |
No |
|
N/A |
No |
|
N/A |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
|
N/A |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
|
Yes |
No |
若要更改公开的终结点,请使用以下特定于技术的 和 属性:include
exclude
Property | Default |
---|---|
|
|
|
|
|
|
|
|
例如,要通过 HTTP 公开除 env和endpoints 之外的所有内容
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
*
在 YAML 中具有特殊含义,因此如果要包含(或排除)所有端点,请务必添加引号,如以下示例所示:
management:
endpoints:
web:
exposure:
include: "*"
2.3. 保护 HTTP 端点
如果您希望为 HTTP 端点配置自定义安全性,例如,仅允许具有特定角色的用户访问它们,Spring Boot 提供了一些可以与 Spring Security 结合使用的方便对象。
@Configuration(proxyBeanMethods = false)
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
http.httpBasic();
}
}
2.4. 配置端点
端点会自动缓存对不采用任何参数的读取作的响应。 若要配置端点缓存响应的时间量,请使用其属性。 以下示例将端点缓存的生存时间设置为 10 秒:
management.endpoint.beans.cache.time-to-live=10s
3. 通过 HTTP 进行监控和管理
3.1. 自定义管理端点路径
management.endpoints.web.base-path=/manage
3.2. 自定义管理服务器端口
management.server.port=8081
3.4. 自定义管理服务器地址
以下示例不允许远程管理连接
management.server.port=8081
management.server.address=127.0.0.1
3.5. 禁用 HTTP 端点
如果您不想通过 HTTP 公开端点,可以将管理端口设置为 ,如以下示例所示:-1
management.server.port=-1
这也可以使用该属性来实现,如以下示例所示:management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.exclude=*
示例:
1.默认情况

2.只开启
/actuator/beans 和 /actuator/mappings 这两个 api
management:
endpoints:
web:
exposure:
include: beans,mappings
3.
3.只关闭
# 开启所有的 api(但不包含 shutdown) management.endpoints.web.exposure.include=* # 关闭/actuator/beans 这个 api management.endpoints.web.exposure.exclude=beans
management:
endpoints:
web:
exposure:
include: '*'
exclude: beans
4.禁用
management:
endpoints:
web:
exposure:
exclude: '*'
management:
server:
port: -1