检测活动/就绪执行器端点执行并收集其结果以将其发送到端点

Detect liveness / readiness actuator endpoint execution and collect its result to send it to an endpoint

我有一个 Spring Boot 2.3.1 应用程序,执行器部署在 Kubernetes 上,相应的 K8s 探针映射到执行器端点:

livenessProbe:
  httpGet:
    path: /actuator/health/liveness
    ...

readinessProbe:
  httpGet:
    path: /actuator/health/readiness
    ...

我想检测 K8s 何时调用每个探测器,获取执行结果和其他一些信息(pod 名称...)并将其发送到 http 端点。

如何检测这些调用并访问其结果?是否有某种 Spring hook/listener 允许我这样做?

这可能不是解决您问题的最优雅的方法,但可以解决问题。

简单拦截执行器调用,响应发送后做你需要做的事

@Component
public class ActuatorHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

  private static final Logger logger = LoggerFactory
      .getLogger(ActuatorHandlerInterceptorAdapter.class);

  @Override
  public void afterCompletion(HttpServletRequest request,
      HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    if (request.getRequestURL().toString().contains("actuator/health/liveness")){
      System.out.println("Let's do something based on liveness response");
    }
    if (request.getRequestURL().toString().contains("actuator/health/readiness")){
      System.out.println("Let's do something based on readiness response");
    }
  }

}

Webflux 应用程序的等价物是:

@Component
public class ActuatorHealthWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerWebExchange exc = exchange;
        if(exchange.getRequest().getURI().toString().contains("/actuator/health")){
            exc = exchange.mutate().response(new ServerHttpResponseDecorator(exchange.getResponse()) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    Mono<DataBuffer> buffer = Mono.from(body);
                    return super.writeWith(buffer.doOnNext(dataBuffer -> {
                        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
                            Channels.newChannel(byteArrayOutputStream).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
                            String responseBody = byteArrayOutputStream.toString(UTF_8);
                            System.out.println(responseBody);
                            //TODO Do something with the response info
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }));
                }
            }).build();
        }
        return chain.filter(exc);
    }
}