Spring Boot 2 健康执行器默认映射

作者:编程家 分类: spring 时间:2025-09-18

Spring Boot 2 提供了一个健康执行器,默认情况下,它会将健康检查的端点映射到 `/actuator/health` 路径下。这个健康执行器可以帮助我们监控应用程序的运行状态,检查各个组件的健康情况,以及提供对健康检查端点的自定义配置。本文将介绍如何使用 Spring Boot 2 的健康执行器,并提供案例代码进行演示。

## 引入依赖

首先,我们需要在 Maven 或 Gradle 项目中引入 Spring Boot Actuator 的依赖。在 `pom.xml`(或 `build.gradle`)文件中添加以下依赖项:

xml

org.springframework.boot

spring-boot-starter-actuator

## 配置健康执行器端点

默认情况下,Spring Boot 2 的健康执行器会将健康检查的端点映射到 `/actuator/health` 路径下。我们可以通过配置文件或代码方式来自定义端点的路径和属性。

### 配置文件方式

在 `application.properties`(或 `application.yml`)文件中添加以下配置:

properties

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

management.endpoints.web.path-mapping.health=health-check

以上配置将把健康检查的端点路径设置为 `/actuator/health-check`。

### 代码方式

我们也可以通过代码方式来配置健康执行器端点的路径和属性。在 Spring Boot 应用程序的配置类中添加以下配置:

java

@Configuration

public class ActuatorConfig {

@Bean

public HealthEndpoint healthEndpoint() {

return new HealthEndpoint();

}

@Bean

public WebEndpointRegistrar webEndpointRegistrar() {

return new WebEndpointRegistrar();

}

@Bean

public WebMvcEndpointHandlerMapping webMvcEndpointHandlerMapping(

WebEndpointDiscoverer webEndpointDiscoverer,

EndpointMediaTypes endpointMediaTypes,

CorsConfigurationProperties corsProperties) {

return new WebMvcEndpointHandlerMapping(webEndpointDiscoverer, endpointMediaTypes,

corsProperties, new EndpointPathResolver(), new MvcEndpointPathProvider(),

Collections.emptyList());

}

}

以上代码将健康检查的端点路径设置为 `/actuator/health`。

## 使用健康执行器

一旦我们配置好了健康执行器的端点路径,就可以使用它来监控应用程序的运行状态了。我们可以通过 HTTP 请求访问健康检查端点,并获取应用程序的健康情况。

下面是一个简单的案例代码,演示如何使用健康执行器:

java

@RestController

public class HealthCheckController {

@Autowired

private HealthEndpoint healthEndpoint;

@GetMapping("/health-check")

public ResponseEntity healthCheck() {

Health health = healthEndpoint.health();

HttpStatus status = determineHttpStatus(health.getStatus());

return new ResponseEntity<>(health, status);

}

private HttpStatus determineHttpStatus(Status status) {

if (status.equals(Status.UP)) {

return HttpStatus.OK;

} else if (status.equals(Status.DOWN)) {

return HttpStatus.SERVICE_UNAVAILABLE;

} else {

return HttpStatus.INTERNAL_SERVER_ERROR;

}

}

}

在上述代码中,我们通过注入 `HealthEndpoint` 来获取应用程序的健康情况。然后,根据健康状态来确定 HTTP 响应的状态码。

##

通过 Spring Boot 2 的健康执行器,我们可以方便地监控应用程序的健康状态,并获取相关的健康检查信息。我们可以通过配置文件或代码方式来自定义健康执行器端点的路径和属性。使用健康执行器可以帮助我们及时发现和解决应用程序的健康问题,提高系统的可靠性和稳定性。

本文介绍了如何使用 Spring Boot 2 的健康执行器,默认情况下,它将健康检查的端点映射到 `/actuator/health` 路径下。我们可以通过配置文件或代码方式来自定义端点的路径和属性。通过案例代码的演示,我们了解了如何使用健康执行器来监控应用程序的运行状态,并获取相关的健康检查信息。使用健康执行器可以帮助我们及时发现和解决应用程序的健康问题,提高系统的可靠性和稳定性。

希望本文对大家了解 Spring Boot 2 的健康执行器有所帮助。如有疑问或意见,请随时留言。