在Spring docs Open API的执行器端点中添加默认响应代码可以通过以下步骤实现:
HealthEndpoint
类,继承自Spring Boot的HealthEndpoint
类,并重写getHealth
方法。import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.boot.actuate.health.StatusAggregator;
import org.springframework.boot.actuate.health.StatusContributor;
import org.springframework.boot.actuate.health.StatusEndpoint;
import org.springframework.boot.actuate.health.StatusEndpointWebExtension;
import org.springframework.stereotype.Component;
@Component
public class CustomHealthEndpoint extends HealthEndpoint {
public CustomHealthEndpoint(HealthIndicator healthIndicator, StatusAggregator statusAggregator) {
super(healthIndicator, statusAggregator);
}
@Override
public Health getHealth(boolean includeDetails) {
Health health = super.getHealth(includeDetails);
Status status = health.getStatus();
if (status.equals(Status.UNKNOWN)) {
// 添加默认响应代码
health = Health.status(Status.UP).build();
}
return health;
}
}
CustomHealthEndpoint
类注入为一个Bean。import org.springframework.boot.actuate.health.StatusAggregator;
import org.springframework.boot.actuate.health.StatusEndpoint;
import org.springframework.boot.actuate.health.StatusEndpointWebExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public CustomHealthEndpoint customHealthEndpoint(HealthIndicator healthIndicator, StatusAggregator statusAggregator) {
return new CustomHealthEndpoint(healthIndicator, statusAggregator);
}
}
application.properties
或application.yml
配置文件中,启用执行器端点。management.endpoints.web.exposure.include=health
现在,当访问执行器端点/health
时,如果原始响应的状态为UNKNOWN,将会返回一个默认的健康状态为UP的响应。
注意:以上代码示例中,CustomHealthEndpoint
类继承自HealthEndpoint
类,这是Spring Boot 2.x版本的实现方式。如果你使用的是Spring Boot 1.x版本,可以继承自AbstractHealthIndicator
类,并实现doHealthCheck
方法来达到相同的效果。