16.1 Actuator概览

16.1 Actuator概览

在机器领域中,执行机构(Actuator)指的是负责控制和移动装置的组件。在Spring Boot应用中,Spring Boot Actuator扮演了相同的角色,它能够让我们看到一个运行中的应用的内部状况,而且能够在一定程度上控制应用的行为。

通过Actuator暴露的端点,我们可以获取一个正在运行中的应用的内部状态。

  • 在应用环境中,都有哪些可用的配置属性?
  • 在应用中,各个源码包的日志级别是什么?
  • 应用消耗了多少内存?
  • 给定的HTTP端点被请求了多少次?
  • 应用本身以及与它协作的外部服务的健康状况如何?

为了在Spring Boot应用中启用Actuator,我们需要在构建文件中添加对Actuatorstarter的依赖。在Spring Boot应用的Maven pom.xml文件中,添加如下的<dependency>条目就能完成该任务:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

将Actuator starter添加到项目的构建文件中之后,应用就会具备一些开箱即用的Actuator端点,其中一部分如表16.1所示。

表16.1 探查运行中Spring Boot应用的状态并对其进行操作的Actuator端点

epub_29101559_120

按照上述属性,要获取应用的健康信息,我们需要向“/management/health”发送GET请求。

16.1.2 启用和禁用Actuator端点

你可能已经发现,默认情况下,只有“/health”和“/info”端点是启用的。大多数Actuator端点会携带敏感信息,所以应该保护起来。我们可以使用SpringSecurity来锁定Actuator,但是因为Actuator本身没有安全保护,所以大多数端点默认都是禁用的,需要我们来选择对外暴露哪些端点。

有两个配置属性能够控制对外暴露哪些端点,它们分别是management.endpoints.web.exposure.include和management.endpoints.web.exposure.exclude。通过management.endpoints.web. exposure.include属性,我们可以指定哪些端点想要暴露出来。例如,想要暴露“/health”“/info”“/beans”和“/conditions”的话,我们可以通过如下的配置来声明:

1
2
3
4
5
management:
endpoints:
web:
exposure:
include: health,info,beans,conditions

management.endpoints.web.exposure.include属性也可以接受星号(*)作为通配符,表明所有的Actuator端点都会对外暴露:

1
2
3
4
5
management:
endpoints:
web:
exposure:
include: '*'

如果除了个别端点之外,我们想暴露其他的所有端点,那么一般来讲更简单的方式是通过通配符将它们全部包含进来,然后明确排除一部分。例如,我们想要暴露除了“/threaddump”和“/heapdump”之外的端点,那么可以按照如下的形式同时设置management.endpoints.web.exposure.include和management.endpoints.web.exposure.exclude属性:

1
2
3
4
5
6
management:
endpoints:
web:
exposure:
include: '*'
exclude: threaddump,heapdump

如果你决定对外公开比“/health”和“/info”更多的信息,那么最好配置SpringSecurity来限制对其他端点的访问。我们将会在16.4节中了解如何保护Actuator端点。现在,我们看一下如何消费Actuator对外暴露的HTTP端点。