Spring Boot自定义Actuator端点:Health.down()为何默认不返回503?
自定义Actuator端点返回DOWN时状态码为200而非503的问题解决
为什么默认返回200?
Spring Boot Actuator的健康端点(包括自定义健康端点)默认就会返回200状态码——这是框架的设计逻辑:端点本身能正常接收并处理请求,就返回200表示「端点可达」;而DOWN只是业务层面的健康状态,只会体现在响应体的status字段里,和HTTP状态码是两个独立的维度。
如何改成返回503或自定义状态码?
有两种实用方案:
方案1:全局配置健康状态与HTTP状态码映射
在配置文件(application.properties或application.yml)里设置健康状态对应的HTTP状态码,这个配置会对所有健康端点生效:
properties格式:
management.health.status.http-mapping.DOWN=503 management.health.status.http-mapping.OUT_OF_SERVICE=503 management.health.status.http-mapping.UP=200
yaml格式:
management: health: status: http-mapping: DOWN: 503 OUT_OF_SERVICE: 503 UP: 200
方案2:单个自定义端点单独设置状态码
如果只想让某个特定的自定义健康端点返回指定状态码,可以在端点方法里用WebEndpointResponse包装健康结果,手动指定状态码:
import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse; import org.springframework.stereotype.Component; @Component @Endpoint(id = "custom") public class CustomHealthEndpoint { @ReadOperation public WebEndpointResponse<Health> getCustomHealth() { Health health = Health.down().build(); // 根据健康状态匹配对应的HTTP状态码 int responseCode = Health.Status.DOWN.equals(health.getStatus()) ? 503 : 200; return new WebEndpointResponse<>(health, responseCode); } }
验证效果
配置或修改代码后重启服务,再次请求http://localhost:8080/actuator/custom,当健康状态为DOWN时,HTTP响应状态码会变成503,响应体依然保留{"status":"DOWN"}。
内容的提问来源于stack exchange,提问作者hrvojet
相关产品推荐
相关产品推荐

