0

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

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

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

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

我如何检测这些调用并访问其结果?是否有某种 Spring 钩子/侦听器可以让我这样做?

4

2 回答 2

0

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);
    }
}
于 2020-07-08T07:20:50.037 回答
0

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

只需拦截执行器调用并在发送响应后执行您需要执行的操作。

@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");
    }
  }

}
于 2020-07-07T09:28:01.517 回答