Actuator概览
在机器领域中,执行机构(actuator)指的是负责控制和移动装置的组件。在Spring Boot应用中,Spring Boot Actuator扮演了相同的角色,它能够让我们看到一个运行中的应用的内部状况,而且能够在一定程度上控制应用的行为。
通过Actuator暴露的端点,我们可以获取一个正在运行中的应用的内部状态,如以下信息。
-
在应用环境中,都有哪些可用的配置属性?
-
在应用中,各个源码包的日志级别是什么?
-
应用消耗了多少内存?
-
给定的HTTP端点被请求了多少次?
-
应用本身以及与它协作的外部服务的健康状况如何?
为了在Spring Boot应用中启用Actuator,我们需要在构建文件中添加对Actuator starter的依赖。在Spring Boot应用的Maven pom.xml文件中添加如下的<dependency>条目就能实现该目的:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
将Actuator starter添加到项目的构建文件中后,应用就会具备一些“开箱即用”的Actuator端点,其中一部分如表15.1所示。

除了基于HTTP的端点之外,表15.1中除“/heapdump”的其他端点都以JMX MBean的形式对外暴露了出来。我们会在第17章学习基于JMX的Actuator。
配置Actuator的基础路径
默认情况下,表15.1中所有端点的路径都会带有“/actuator”前缀。这意味着,如果我们想要通过Actuator获取应用的健康信息,那么向“/actuator/health”发送GET请求即可。
Actuator的路径前缀可以通过设置management.endpoint.web.base-path属性来修改。例如,想要将前缀设置为“/management”,可以通过如下的方式来设置management. endpoint.web.base-path属性:
management:
endpoints:
web:
base-path: /management
按照上述属性,要获取应用的健康信息,需要向“/management/health”发送GET请求。
无论是否改变Actuator的基础路径,为简洁起见,本章中所有的Actuator端点都不包含基础路径。例如,“/health”端点指的是“/{base path}/health”,更准确地说,如果基础路径没有被改变过,那么该端点指向的应该是“/actuator/health”。
启用和禁用Actuator端点
默认情况下,只有“/health”端点是启用的。大多数Actuator端点会携带敏感信息,应该被保护起来。我们可以使用Spring Security来锁定Actuator,但Actuator本身没有安全保护,所以大多数端点默认都是禁用的,需要我们选择对外暴露哪些端点。
有两个配置属性能够控制对外暴露哪些端点,分别是management.endpoints.web. exposure.include和management.endpoints.web.exposure.exclude。通过management.endpoints. web.exposure.include属性,可以指定想要暴露的端点。例如,想要暴露“/health”“/info”“/beans”和“/conditions”端点,可以通过如下的配置来声明:
management:
endpoints:
web:
exposure:
include: health,info,beans,conditions
management.endpoints.web.exposure.include属性也可以接受星号(*)作为通配符,表明所有的Actuator端点都会对外暴露:
management:
endpoints:
web:
exposure:
include: '*'
如果我们想暴露除了个别端点外的所有端点,那么一般来讲更简单的方式是通过通配符将它们全部包含,然后明确排除一部分。例如,我们想要暴露除了“/threaddump”和“/heapdump”之外的端点,那么可以按照如下的形式同时设置management.endpoints. web.exposure.include和management.endpoints.web.exposure.exclude属性:
management:
endpoints:
web:
exposure:
include: '*'
exclude: threaddump,heapdump
如果想要对外公开比“/health”和“/info”更多的信息,那么最好配置Spring Security来限制对其他端点的访问。我们会在15.4节中了解如何保护Actuator端点。现在,我们看一下如何消费Actuator对外暴露的HTTP端点。