Search code examples
springspring-bootspring-boot-actuatorspring-cloud-kubernetes

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


I have a Spring Boot 2.3.1 application with actuator deployed on Kubernetes with the corresponding K8s probes mapped against the actuator endpoints:

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

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

I'd like to detect when K8s invokes each of the probes, get the execution result and some other pieces of info (pod name...) and send it to an http endpoint.

How could I detect those invocations and access its result? Is there some kind of Spring hook/listener that allows me to do it?


Solution

  • This may not be the most elegant solution to your problem, but will do the trick.

    Simply intercept the actuator call and do what you need to do after the response is sent.

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