Jersey HK2 : Dependency injection and healthchecks

Viewed 93

My app has got quite a few of async (cron) processes and they all have their separate binder classes in Jersey. These processes are started and managed through independent scripts.

Now, if I make a change in the classes used by these processes, (e.g. add a dependency in the classes) and forget to update the binder class inadvertently, the processes still start up but fail with org.glassfish.hk2.api.UnsatisfiedDependencyException (which is expected). However, this does not stop the process on the node and monitoring tool still thinks that the process is running fine.

I am looking to implement Healthchecks in these process so that I can see if the process has come up fine after deployment and is able to start without any dependency error. I am exploring following options:

  • An async lightweight process that exports ServiceLocator health status to a monitoring system (e.g. prometheus)
  • An API endpoint that can be polled externally and returns response based on ServiceLocator status

I have got a couple of questions:

  • Is there a native way in Jersey HK2 to do this?
  • How do I know if Locator is able to resolve all the dependencies (i.e. there is no UnsatisfiedDependencyException)?
1 Answers

In hk2 there is a special service called the ErrorService which you can use to see if there are failures creating services. Since hk2 is a dynamic framework this error service implementation will not get called until someone attempts to create the service that is failing.

You also might want to seriously look into the automatic binding options of hk2. Makes everything so much easier IMO. See the section on Automatic Service Population

Here is an example of using the ErrorService:

@Service
public class ExampleErrorService implements ErrorService {

    @Override
    public void onFailure(ErrorInformation ei) throws MultiException {
        if (ErrorType.SERVICE_CREATION_FAILURE.equals(ei.getErrorType())) {
            // Tell your health check service there was an exception
            return;
        }
            
        // Maybe log other failures?
        
    }
    
}
Related