gpt4 book ai didi

spring-boot - 如何实现自定义 CompositeHealthContributor

转载 作者:行者123 更新时间:2023-12-03 16:50:24 33 4
gpt4 key购买 nike

我想显示以下健康信息:

{
"status":"UP",
"components": {
"myHealthComposite": {
"status":"UP",
"components": {
"myFirstHealthIndicator": { "status":"UP" },
"mySecondHealthIndicator": { "status":"UP" }
}
}
},
"groups":[]
}

从最新的 Spring Boot Actuator 文档中,我应该使用“HealthIndicator”-Interface 实现“myFirstHealthIndactor”和“mySecondHealthIndicator”,并将它们与“CompositeHealthContributor”-Interface 组合起来。但是对于“CompositeHealthContributor”,我需要一个示例,在文档中我找不到对我有用的东西。

有人可以帮我吗?

你好

编辑:

myFirstHealthIndicator
@Component
public class MyFirstHealthIndicator implements HealthIndicator {

@Override
public Health health() {
return Health.up().build();
}

}

mySecondHealthIndicator
@Component
public class MySecondHealthIndicator implements HealthIndicator {

@Override
public Health health() {
return Health.up().build();
}

}

myHealthComposite
@Component
public class MyHealthComposite implements CompositeHealthContributor {

@Override
public HealthContributor getContributor(String name) {
return null;
}

@Override
public Iterator<NamedContributor<HealthContributor>> iterator() {
return null;
}

}

最佳答案

一个非常简单和硬编码的解决方案,输出预期。

请删除 @Component注释来自 MyFirstHealthIndicator MySecondHealthIndicator .否则,它们也会作为单独的组件列出。

MyFirstHealthIndicator

public class MyFirstHealthIndicator implements HealthIndicator {

@Override
public Health health() {
return Health.up().build();
}

}

MySecondHealthIndicator

public class MySecondHealthIndicator implements HealthIndicator {

@Override
public Health health() {
return Health.up().build();
}

}

MyHealthComposite

@Component
public class MyHealthComposite implements CompositeHealthContributor {

private Map<String, HealthContributor> contributors = new LinkedHashMap<>();

MyHealthComposite() {
this.contributors.put("myFirstHealthIndicator", new MyFirstHealthIndicator());
this.contributors.put("mySecondHealthIndicator", new MySecondHealthIndicator());
}

@Override
public HealthContributor getContributor(String name) {
return contributors.get(name);
}

@Override
public Iterator<NamedContributor<HealthContributor>> iterator() {
return contributors.entrySet().stream()
.map((entry) -> NamedContributor.of(entry.getKey(), entry.getValue())).iterator();
}
}

请启用 management.endpoint.health.show-components=always在您的 application.properties .

输出看起来像:

{
"status": "UP",
"components": {
"diskSpace": {
"status": "UP"
},
"myHealthComposite": {
"status": "UP",
"components": {
"myFirstHealthIndicator": {
"status": "UP"
},
"mySecondHealthIndicator": {
"status": "UP"
}
}
},
"ping": {
"status": "UP"
}
}
}

但是,这不是我的解决方案,而是从 BindersHealthIndicatorAutoConfiguration from spring-cloud-stream 采用的并适应要求。

关于spring-boot - 如何实现自定义 CompositeHealthContributor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138614/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com