Initialization

edit

A RestClient instance can be built through the corresponding RestClientBuilder class, created via RestClient#builder(HttpHost...) static method. The only required argument is one or more hosts that the client will communicate with, provided as instances of HttpHost as follows:

RestClient restClient = RestClient.builder(
        new HttpHost("localhost", 9200, "http"),
        new HttpHost("localhost", 9201, "http")).build();

The RestClient class is thread-safe and ideally has the same lifecycle as the application that uses it. It is important that it gets closed when no longer needed so that all the resources used by it get properly released, as well as the underlying http client instance and its threads:

restClient.close();

RestClientBuilder also allows to optionally set the following configuration parameters while building the RestClient instance:

setDefaultHeaders
default headers that need to be sent with each request, to prevent having to specify them with each single request
setMaxRetryTimeoutMillis
the timeout that should be honoured in case multiple attempts are made for the same request. The default value is 10 seconds, same as the default socket timeout. In case the socket timeout is customized, the maximum retry timeout should be adjusted accordingly
setFailureListener
a listener that gets notified every time a node fails, in case actions need to be taken. Used internally when sniffing on failure is enabled
setRequestConfigCallback
callback that allows to modify the default request configuration (e.g. request timeouts, authentication, or anything that the org.apache.http.client.config.RequestConfig.Builder allows to set)
setHttpClientConfigCallback
callback that allows to modify the http client configuration (e.g. encrypted communication over ssl, or anything that the org.apache.http.impl.nio.client.HttpAsyncClientBuilder allows to set)