Spring Boot Actuator简介

      Spring Boot Actuator端点通过 JMX 和HTTP 公开暴露给外界访问,大多数时候我们使用基于HTTP的Actuator端点,因为它们很容易通过浏览器、CURL命令、shell脚本等方式访问。

一些有用的执行器端点是:

  1. /beans:此端点返回应用程序中配置的所有bean的列表。
  2. /env:提供有关Spring Environment属性的信息。
  3. /health:显示应用程序运行状况
  4. /info:显示应用程序信息,我们可以在Spring环境属性中配置它。
  5. /mappings:显示所有 @RequestMapping 路径 的列表
  6. /shutdown:允许我们正常关闭应用程序。
  7. /threaddump:提供应用程序的线程转储。

你可以从 此处 获得Spring执行器端点的完整列表

Spring Actuator端点安全

     只有“/health”和“/info”端点暴露在没有任何安全性的情况下,为了访问我们需要配置Spring安全。 这很容易实现,我们将在本教程的后半部分介绍它。

启用S​​pring Actuator端点

当我们将Spring Actuator Dependencies添加到我们的Spring启动项目时,它会自动启用执行器端点。将以下依赖项添加到Spring应用程序以启用Spring启动执行器端点。


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

现在,当你运行应用程序时,你将看到执行器端点映射到日志中。

 2 endpoint(s) beneath base path '/actuator'
: Mapped "{[/actuator/health],methods=[GET]

请注意,只有两个端点 - health info 已映射。

下图显示了这些执行器端点的输出。

是否注意到 /actuator/info 没有数据这是因为我们还没有配置它们。 只需在 application.properties 文件中 添加以下属性即可


info.app.name=Spring Actuator Example
info.app.java.version=10
info.app.type=Spring Boot

重新启动应用程序,就能够获得上面信息了。

 

自定义执行器端点基本路径

默认情况下,执行器端点的基本路径是 /actuator ,我们可以通过 management.endpoints.web.base-path 在应用程序属性文件中 设置将其更改为任何其他值


management.endpoints.web.base-path=/management

暴露其他执行器端点

我们可以通过属性文件启用和禁用其他执行器端点。

如果要启用所有执行器端点,请添加以下属性。


management.endpoints.web.exposure.include=*

要仅启用特定的执行器端点,请提供端点ID列表。


management.endpoints.web.exposure.include=health,info,beans,env

执行器端点的Srping安全性

请注意,我们需要将 Spring Security 添加 到我们的应用程序中以启用其他端点,因为所有其他端点至少需要基本身份验证。

在应用程序中为spring security添加以下依赖项。


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

另外,在应用程序属性文件中添加spring安全性用户名和密码。


spring.security.user.name=pankaj
spring.security.user.password=pankaj

重新启动应用程序,将看到正在映射的其他端点。

现在,当尝试访问安全的执行器端点时,你必须提供登录凭据。

Spring执行器自定义端点

Spring Framework的 一个重要特性 是它很容易扩展。 我们可以使用 @Endpoint 类上的注释 创建自己的自定义执行器端点 然后我们必须 在方法上 使用 @ReadOperation @WriteOperation @DeleteOperation 注释将它们公开为执行器端点bean。

我们可以使用 @JmxEndpoint @WebEndpoint 注释 创建特定于技术的端点

以下是我们自定义Spring执行器端点的示例。


package com.samplesjdon.spring;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Endpoint(id="myendpoint")
@Component
public class MyCustomEndpoints {

	@ReadOperation
	@Bean
	public String hi() {
		return "Hi from custom endpoint";
	}
}

你是否注意到端点ID? 我们还需要在要启用的执行器端点列表中配置它。

更新 application.properties 文件中的 以下属性


management.endpoints.web.exposure.include=health,info,beans,env,myendpoint

现在,当你启动应用程序时,请检查日志中映射的新端点。

 

总结

Spring Boot Actuator是一个生产就绪的管理和信息模块。 我们可以轻松扩展它以添加我们自己的API并管理我们的应用程序。

 

Spring Boot