Spring Boot 3中如何编程式添加HealthIndicator到存活就绪健康组
在Spring Boot 3中编程方式将自定义HealthIndicator添加到存活/就绪健康组
可以通过编程方式实现,核心是利用HealthEndpointGroupsCustomizer接口或自定义Customizer<HealthEndpointGroups> Bean来显式将你的自定义HealthIndicator添加到目标健康组。以下是具体实现步骤:
1. 定义自定义HealthIndicator
首先创建你的自定义健康检查类,作为Spring Bean:
@Component public class MyCustomHealthIndicator implements HealthIndicator { @Override public Health health() { // 替换为你的实际健康检查逻辑 return Health.up() .withDetail("custom-check", "success") .build(); } }
2. 编程配置健康组
通过自定义组配置器,将上述Indicator添加到liveness和readiness组:
方式一:实现HealthEndpointGroupsCustomizer接口
@Component public class CustomHealthGroupConfig implements HealthEndpointGroupsCustomizer { private final MyCustomHealthIndicator customHealthIndicator; // 构造注入自定义Indicator public CustomHealthGroupConfig(MyCustomHealthIndicator customHealthIndicator) { this.customHealthIndicator = customHealthIndicator; } @Override public void customize(HealthEndpointGroups groups) { // 将自定义Indicator添加到存活组 groups.get("liveness").addIndicator(customHealthIndicator); // 将自定义Indicator添加到就绪组 groups.get("readiness").addIndicator(customHealthIndicator); } }
方式二:定义Customizer<HealthEndpointGroups> Bean
@Configuration public class HealthGroupConfiguration { @Bean public Customizer<HealthEndpointGroups> healthGroupCustomizer(MyCustomHealthIndicator customHealthIndicator) { return groups -> { groups.get("liveness").addIndicator(customHealthIndicator); groups.get("readiness").addIndicator(customHealthIndicator); }; } }
关键说明
单独将HealthIndicator定义为Bean不会自动加入liveness或readiness组,因为Spring Boot 3的默认健康组有固定的包含范围:
liveness组默认仅包含StateHealthIndicator(用于检查应用存活状态)readiness组默认包含StateHealthIndicator和DiskSpaceHealthIndicator
必须通过上述编程方式显式将自定义Indicator添加到对应组,才能让健康端点返回包含自定义检查结果的组信息。
内容的提问来源于stack exchange,提问作者mingjun
相关产品推荐
相关产品推荐

