首页 > 解决方案 > SpringBoot:健康端点中缺少领事健康指标

问题描述

我有一个基于 SpringBoot 的 Web 应用程序,它公开了一个 consul 健康指示器 bean。
bean 由 springboot 的自动配置正确创建和初始化,但是,尽管关联的配置属性“management.health.consul.enabled”设置为 true,但指标并未显示在执行器健康端点中:

{
   "status": "UP",
   "components": {
        "Kafka": {...},
        "SchemaRegistry": {...},
        "discoveryComposite": {...},
        "diskSpace": {...},
        "ping": {...},
        "refreshScope": {...}
    }
}

经过进一步检查,我发现了负责获取所有可用指标的波纹管片段(HealthEndpointConfiguration.java):

    @Bean
    @ConditionalOnMissingBean
    HealthContributorRegistry healthContributorRegistry(ApplicationContext applicationContext,
            HealthEndpointGroups groups) {
        Map<String, HealthContributor> healthContributors = new LinkedHashMap<>(
                applicationContext.getBeansOfType(HealthContributor.class));
        if (ClassUtils.isPresent("reactor.core.publisher.Flux", applicationContext.getClassLoader())) {
            healthContributors.putAll(new AdaptedReactiveHealthContributors(applicationContext).get());
        }
        return new AutoConfiguredHealthContributorRegistry(healthContributors, groups.getNames());
    }

在那里设置一个断点,我看到 ConsulHealthIndicator bean 确实没有列在applicationContext.getBeansOfType(HealthContributor.class)调用的输出中,如下所示:

在此处输入图像描述

但是,当我使用父应用程序上下文测试相同的调用时,我得到以下信息: AnnotationConfigApplicationContext

有人可以解释一下为什么这个特定的bean出现在根上下文中而不是子上下文中吗?

有没有办法强制它在子上下文中初始化,以便在健康端点中正确注册?

我目前正在使用

先感谢您。


编辑

我附上了一个允许重现问题的示例项目。
我还包含了应用程序使用的 consul 配置(您可以通过 consul import 命令导入它)。
运行上面的示例并转到健康端点(localhost:8080/monitoring/health),您将清楚地看到列表中缺少 consul 组件。

标签: javaspringspring-bootspring-boot-actuator

解决方案


为了让 consul 指标正常工作,我必须提供自己的 HealthContributorRegistry ,在执行 HealthContributor bean 查找时,我会在其中考虑父上下文:

  @Bean
  HealthContributorRegistry healthContributorRegistry(
      ApplicationContext applicationContext, HealthEndpointGroups groups) {
    Map<String, HealthContributor> healthContributors =
        new LinkedHashMap<>(applicationContext.getBeansOfType(HealthContributor.class));
    ApplicationContext parent = applicationContext.getParent();
    while (parent != null) {
      healthContributors.putAll(parent.getBeansOfType(HealthContributor.class));
      parent = parent.getParent();
    }
    return new DefaultHealthContributorRegistry(healthContributors);
  }

这是一个临时的解决方法,理想情况下,领事指标应该像其他健康贡献者一样开箱即用。


推荐阅读