7.1.5 Configuring HTTP clients

Global Configuration for All Clients

The default HTTP client configuration is a Configuration Properties called DefaultHttpClientConfiguration that allows configuring the default behaviour for all HTTP clients. For example, in application.yml:

Altering default HTTP client configuration

  1. micronaut:
  2. http:
  3. client:
  4. read-timeout: 5s

The above example sets of readTimeout property of the HttpClientConfiguration class.

Client Specific Configuration

If you wish to have a separate configuration per client then there a couple of options. You can configure Service Discovery manually in application.yml and apply per-client configuration:

Manually configuring HTTP services

  1. micronaut:
  2. http:
  3. services:
  4. foo:
  5. urls:
  6. - http://foo1
  7. - http://foo2
  8. read-timeout: 5s (1)
1The read timeout is applied to the foo client.

WARN: This client configuration can be used in conjunction with the @Client annotation, either by injecting an HttpClient directly or use on a client interface. In any case, all other attributes on the annotation will be ignored other than the service id.

Then simply inject the named client configuration:

Injecting an HTTP client

  1. @Client("foo") @Inject RxHttpClient httpClient;

You can also simply define a bean that extends from HttpClientConfiguration and ensuring that the javax.inject.Named annotation is used to name it appropriately:

Defining an HTTP client configuration bean

  1. @Named("twitter")
  2. @Singleton
  3. class TwitterHttpClientConfiguration extends HttpClientConfiguration {
  4. public TwitterHttpClientConfiguration(ApplicationConfiguration applicationConfiguration) {
  5. super(applicationConfiguration);
  6. }
  7. }

This configuration will then be picked up if you inject a service called twitter using @Client using Service Discovery:

Injecting an HTTP client

  1. @Client("twitter") @Inject RxHttpClient httpClient;

Alternatively if you are not using service discovery then you can use the configuration member of @Client to refer to a specific type:

Injecting an HTTP client

  1. @Client(value="https://api.twitter.com/1.1",
  2. configuration=TwitterHttpClientConfiguration.class)
  3. @Inject
  4. RxHttpClient httpClient;

Using HTTP Client Connection Pooling

If you have a client that needs to handle a significant number of requests then you can benefit from enabling HTTP client connection pooling. The following configuration will enable pooling for the foo client:

Manually configuring HTTP services

  1. micronaut:
  2. http:
  3. services:
  4. foo:
  5. urls:
  6. - http://foo1
  7. - http://foo2
  8. pool:
  9. enabled: true (1)
  10. max-connections: 50 (2)
1Enables the pool
2Sets the maximum number of connections in the pool

See the API for ConnectionPoolConfiguration for details on available options to configure the pool.