SpringbootActuator/SpringbootAdmin添加健康信息

SpringbootActuator可以通过extends AbstractHealthIndicator或者implements HealthIndicator可以新建一个健康信息,但是如果不新建,只添加或覆盖里面信息呢,比如里面有个ping,我想在里面加一条地址信息,而不是重新建一个bean覆盖。extends AbstractHealthIndicator或者implements HealthIndicator会导致覆盖掉原来的bean,而我只想往原来的bean里面添加信息。

以下回答参考GPT并且由Bony-整理:

可以通过实现HealthIndicator接口,并且注入已有的HealthIndicator bean来实现向现有健康信息中添加新的信息。具体步骤如下:
1:实现一个新的HealthIndicator,该类需要注入已有的HealthIndicator bean

@Component
public class MyCustomHealthIndicator implements HealthIndicator {

    private final HealthIndicator delegate;

    public MyCustomHealthIndicator(HealthAggregator healthAggregator, List<HealthIndicator> healthIndicators) {
        this.delegate = new CompositeHealthIndicator(healthAggregator, healthIndicators);
    }

    @Override
    public Health health() {
        Health.Builder builder = new Health.Builder();

        // 获取原有的健康信息
        Health health = delegate.health();

        // 获取原有信息中的某一个状态
        Status status = health.getStatus();

        // 添加新的信息到状态中
        builder.status(status.addDetail("myCustomDetail", "some value"));

        // 返回新的健康信息
        return builder.build();
    }
}

2:在MyCustomHealthIndicator中注入已有的HealthIndicator bean

@Autowired
public MyCustomHealthIndicator(HealthAggregator healthAggregator, List<HealthIndicator> healthIndicators, PingHealthIndicator pingHealthIndicator) {
    this.delegate = new CompositeHealthIndicator(healthAggregator, healthIndicators);
    ((CompositeHealthIndicator) delegate).addHealthIndicator("ping", pingHealthIndicator);
}

其中PingHealthIndicator是默认的HealthIndicator中的一种,它用于检测应用程序是否能够ping通某个主机。这样就可以在现有的健康信息中添加新的信息了。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632