当应用程序健康状态发生变化时运行一些逻辑

You*_*sef 4 java spring spring-boot spring-boot-actuator

我在management.endpoint.health.group (foo, bar)中有多个健康检查

我在 kubernetes 集群中部署我的应用程序,

我想要的是当 kube 向我发送 liveness 请求并且 (foo, bar) 的状态被聚合时,此时(在回复之前)我想基于最后一个状态运行一些逻辑。

我的指标是这样定义的

@Component
public class FooHealthIndicator implements HealthIndicator {
  
  @Override
  public Health health() {

    Health.Builder builder = new Health.Builder();

    try {
      // some foo specific logic
      builder.up();

    } catch (Exception exception) {
      ...
      builder.down().withException(exception);
    }
    return builder.build();
  }
Run Code Online (Sandbox Code Playgroud)

同样适用于BarHealthIndicator

小智 6

您需要做的是实现一个扩展HealthEndpointWebExtension 的组件,并且您可以在其中拦截组聚合状态:

public class HealthEndpointCustomExtension extends HealthEndpointWebExtension {

    private final Map<String,Status> lastStatusByGroup = new HashMap<>();

    public HealthEndpointCustomExtension(HealthContributorRegistry registry, HealthEndpointGroups groups, Duration slowIndicatorLoggingThreshold) {
        super(registry, groups, slowIndicatorLoggingThreshold);
    }

    @Override
    public WebEndpointResponse<HealthComponent> health(ApiVersion apiVersion, WebServerNamespace serverNamespace, SecurityContext securityContext, boolean showAll, String... path) {
        WebEndpointResponse<HealthComponent> response = super.health(apiVersion, serverNamespace, securityContext, showAll, path);

        if (path.length > 0) {
            String group = path[0];
            Status status = response.getBody().getStatus();
            Status lastStatus = lastStatusByGroup.put(group, status);

            if (lastStatus != null && !lastStatus.equals(status)) {
                //..do some logic
            }
        }

        return response;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后你只需在配置类中声明该组件的 bean 工厂方法:

    @Bean
    HealthEndpointWebExtension healthEndpointWebExtension(HealthContributorRegistry healthContributorRegistry,
                                                          HealthEndpointGroups groups, HealthEndpointProperties properties) {
        return new HealthEndpointCustomExtension(healthContributorRegistry, groups,
                properties.getLogging().getSlowIndicatorThreshold());
    }
Run Code Online (Sandbox Code Playgroud)