本文主要研究一下NacosDiscoveryHealthIndicatorAutoConfiguration

NacosDiscoveryHealthIndicatorAutoConfiguration

nacos-spring-boot-project/nacos-discovery-spring-boot-actuator/src/main/java/com/alibaba/boot/nacos/discovery/actuate/autoconfigure/NacosDiscoveryHealthIndicatorAutoConfiguration.java

@Configuration
@ConditionalOnClass({ HealthIndicator.class })
@AutoConfigureBefore({ EndpointAutoConfiguration.class })
@AutoConfigureAfter(NacosDiscoveryAutoConfiguration.class)
@ConditionalOnEnabledHealthIndicator(NacosDiscoveryConstants.ENDPOINT_PREFIX)
public class NacosDiscoveryHealthIndicatorAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public NacosDiscoveryHealthIndicator nacosDiscoveryHealthIndicator() {
        return new NacosDiscoveryHealthIndicator();
    }

}
  • NacosDiscoveryHealthIndicatorAutoConfiguration注册了NacosDiscoveryHealthIndicator

NacosDiscoveryHealthIndicator

nacos-spring-boot-project/nacos-discovery-spring-boot-actuator/src/main/java/com/alibaba/boot/nacos/discovery/actuate/health/NacosDiscoveryHealthIndicator.java

public class NacosDiscoveryHealthIndicator extends AbstractHealthIndicator {

    @Autowired
    private ApplicationContext applicationContext;

    private static final String UP_STATUS = "up";

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        builder.up();
        NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory.getSingleton();
        for (NamingService namingService : nacosServiceFactory.getNamingServices()) {
            if (namingService instanceof NacosServiceMetaData) {
                NacosServiceMetaData nacosServiceMetaData = (NacosServiceMetaData) namingService;
                Properties properties = nacosServiceMetaData.getProperties();
                builder.withDetail(
                        JSON.toJSONString(
                                PropertiesUtils.extractSafeProperties(properties)),
                        namingService.getServerStatus());
            }
            if (!namingService.getServerStatus().equalsIgnoreCase(UP_STATUS)) {
                builder.down();
            }
        }
    }
}
  • NacosDiscoveryHealthIndicator继承了AbstractHealthIndicator,其doHealthCheck方法会遍历namingService,如果namingService为NacosServiceMetaData则将properties的json作为key,serverStatus作为value填充到detail中;接着判断其serverStatus是否为up,不是的话则标记为down

小结

NacosDiscoveryHealthIndicatorAutoConfiguration注册了NacosDiscoveryHealthIndicator;NacosDiscoveryHealthIndicator继承了AbstractHealthIndicator,其doHealthCheck方法会遍历namingService,如果namingService为NacosServiceMetaData则将properties的json作为key,serverStatus作为value填充到detail中;接着判断其serverStatus是否为up,不是的话则标记为down

doc

03-05 18:01