Search code examples
groovymicronaut

What is the difference between Groovy Micronaut's @Client injected RxHttpClient vs RxHttpClient.create?


I'm creating a Micronaut HTTP Client using the @Client annotation in Groovy, and the compiler complains if I use anything other than a static constant. However, this limits me from being able to change the URL per environment by passing in a config value.

So I tried using RxHttpClient.create(myUrl) in my service instead, and the same request I'm making returns a 403. The RxHttpClient docs say

Create a new HttpClient. Note that this method should only be used outside of the context of an application. Within Micronaut use Inject to > inject a client instead.

This doesn't explain why I shouldn't use the create method, and I'm left with an inability to make requests to different servers on different environments. What is the difference between the two clients I'm creating?


Solution

  • The @Client annotation will inject a managed client that has been dependency injected with additional instrumentation features for tracing, propagation etc. By using create Micronaut cannot dependency inject the instance so certain features of the framework won't work.

    In addition with create you have to ensure you manually close the client since Micronaut cannot manage the life cycle and cleanly shutdown the client when the application shuts down.

    Finally regarding using a static constant to @Client, it is not true that this limits you since the value can include placeholders. For example:

    @Client("${my.server}")
    

    Then in application.yml you can configure:

    my:
      server: http://foo.com
    

    Or even better you can use the new HTTP services feature. See https://docs.micronaut.io/latest/guide/index.html#serviceDiscoveryManual