Search code examples
micronaut

Understanding Micronaut 2


Seeking help in understanding what the right pattern is with Micronaut 2. All controller methods now run on NIO Eventloop thread by default. Documentation warns against doing any blocking call on this thread and instead, off load it to a threadpool (using @ExecuteOn or RxJava SubscribeOn) As an example of blocking call, document talks about DB calls or JPA calls.

I have a scenario where I need to call multiple Microservices - so multiple IO calls are involved. I use Declarative client for it by defining an interface etc. Document says that, all HttpClient calls are done on NIO eventloop. But as these Http Calls are blocking, till they get the response, I am a little confused - do I need to off load them to a separate IO pool? Wouldn't the NIO Eventloop thread used by HttpClient block till it executes and gets http response ? I have been using usual return types from my Client interface. Do I then need to return a RxJava type from them ? May be I am overthinking - but am certainly confused as to what the right pattern is when we have to call other microservices from controller methods ? Any help - appreciate it.


Solution

  • The documentation provides an example of a declarative http client.

    @Client("/pets") 
    public interface PetClient extends PetOperations { 
    
        @Override
        Single<Pet> save(String name, int age); 
    }
    

    Notice the return type of the save method which is a Single, it is a non blocking reactive type.

    If you declare the methods in your client with blocking type, the call will be blocking which is not what you want :

    @Client("/pets") 
    public interface PetClient extends PetOperations { 
    
        @Override
        Pet save(String name, int age); //blocking call
    }
    

    You should use non blocking type; at the end of the section I linked, there is a list of response types compatible with @Client.