| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189 | [[java-rest-low-config]]== Common configurationAs explained in <<java-rest-low-usage-initialization>>, the `RestClientBuilder`supports providing both a `RequestConfigCallback` and an `HttpClientConfigCallback`which allow for any customization that the Apache Async Http Client exposes.Those callbacks make it possible to modify some specific behaviour of the clientwithout overriding every other default configuration that the `RestClient`is initialized with. This section describes some common scenarios that requireadditional configuration for the low-level Java REST Client.=== TimeoutsConfiguring requests timeouts can be done by providing an instance of`RequestConfigCallback` while building the `RestClient` through its builder.The interface has one method that receives an instance ofhttps://hc.apache.org/httpcomponents-client-4.5.x/current/httpclient/apidocs/org/apache/http/client/config/RequestConfig.Builder.html[`org.apache.http.client.config.RequestConfig.Builder`] as an argument and has the same return type. The request config builder canbe modified and then returned. In the following example we increase theconnect timeout (defaults to 1 second) and the socket timeout (defaults to 30seconds).["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-config-timeouts]--------------------------------------------------Timeouts also can be set per request with RequestOptions, which overrides RestClient customizeRequestConfig.["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-config-request-options-timeouts]--------------------------------------------------=== Number of threadsThe Apache Http Async Client starts by default one dispatcher thread, and anumber of worker threads used by the connection manager, as many as the numberof locally detected processors (depending on what`Runtime.getRuntime().availableProcessors()` returns). The number of threadscan be modified as follows:["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-config-threads]--------------------------------------------------=== Basic authenticationConfiguring basic authentication can be done by providing an`HttpClientConfigCallback` while building the `RestClient` through its builder.The interface has one method that receives an instance ofhttps://hc.apache.org/httpcomponents-asyncclient-4.1.x/current/httpasyncclient/apidocs/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.html[`org.apache.http.impl.nio.client.HttpAsyncClientBuilder`] as an argument and has the same return type. The http client builder can bemodified and then returned. In the following example we set a defaultcredentials provider that requires basic authentication.["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-config-basic-auth]--------------------------------------------------Preemptive Authentication can be disabled, which means that every request will be sent withoutauthorization headers to see if it is accepted and, upon receiving an HTTP 401 response, it willresend the exact same request with the basic authentication header. If you wish to do this, thenyou can do so by disabling it via the `HttpAsyncClientBuilder`:["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-config-disable-preemptive-auth]--------------------------------------------------<1> Disable preemptive authentication=== Other authentication methods==== Elasticsearch Token Service tokensIf you want the client to authenticate with an Elasticsearch access token, set the relevant HTTP request header.If the client makes requests on behalf of a single user only, you can set the necessary `Authorization` header as a default header as shownin the following example:["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-auth-bearer-token]--------------------------------------------------==== Elasticsearch API keysIf you want the client to authenticate with an Elasticsearch API key, set the relevant HTTP request header.If the client makes requests on behalf of a single user only, you can set the necessary `Authorization` header as a default header as shownin the following example:["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-auth-api-key]--------------------------------------------------=== Encrypted communicationEncrypted communication using TLS can also be configured through the`HttpClientConfigCallback`. Thehttps://hc.apache.org/httpcomponents-asyncclient-4.1.x/current/httpasyncclient/apidocs/org/apache/http/impl/nio/client/HttpAsyncClientBuilder.html[`org.apache.http.impl.nio.client.HttpAsyncClientBuilder`] received as an argument exposes multiple methods to configure encrypted communication: `setSSLContext`, `setSSLSessionStrategy` and `setConnectionManager`, in order of precedence from the least important.When accessing an Elasticsearch cluster that is setup for TLS on the HTTP layer, the client needs to trust the certificate thatElasticsearch is using. The following is an example of setting up the client to trust the CA that has signed the certificate that Elasticsearch is using, when that CA certificate is available in a PKCS#12 keystore:["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-config-encrypted-communication]--------------------------------------------------The following is an example of setting up the client to trust the CA that has signed the certificate that Elasticsearch is using, whenthat CA certificate is available as a PEM encoded file.["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-config-trust-ca-pem]--------------------------------------------------When Elasticsearch is configured to require client TLS authentication, for example when a PKI realm is configured, the client needs to providea client certificate during the TLS handshake in order to authenticate. The following is an example of setting up the client for TLSauthentication with a certificate and a private key that are stored in a PKCS#12 keystore.["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-config-mutual-tls-authentication]--------------------------------------------------If the client certificate and key are not available in a keystore but rather as PEM encoded files, you cannot use themdirectly to build an SSLContext. You must rely on external libraries to parse the PEM key into a PrivateKey instance. Alternatively, youcan use external tools to build a keystore from your PEM files, as shown in the following example:```openssl pkcs12 -export -in client.crt -inkey private_key.pem \        -name "client" -out client.p12```If no explicit configuration is provided, the https://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#CustomizingStores[system default configuration]will be used.=== OthersFor any other required configuration needed, the Apache HttpAsyncClient docsshould be consulted: https://hc.apache.org/httpcomponents-asyncclient-4.1.x/ .NOTE: If your application runs under the security manager you might be subjectto the JVM default policies of caching positive hostname resolutionsindefinitely and negative hostname resolutions for ten seconds. If the resolvedaddresses of the hosts to which you are connecting the client to vary with timethen you might want to modify the default JVM behavior. These can be modified byaddinghttps://docs.oracle.com/javase/8/docs/technotes/guides/net/properties.html[`networkaddress.cache.ttl=<timeout>`]andhttps://docs.oracle.com/javase/8/docs/technotes/guides/net/properties.html[`networkaddress.cache.negative.ttl=<timeout>`]to yourhttps://docs.oracle.com/javase/8/docs/technotes/guides/security/PolicyFiles.html[Javasecurity policy].=== Node selectorThe client sends each request to one of the configured nodes in round-robinfashion. Nodes can optionally be filtered through a node selector that needsto be provided when initializing the client. This is useful when sniffing isenabled, in case no dedicated master nodes should be hit by HTTP requests.For each request the client will run the eventually configured node selectorto filter the node candidates, then select the next one in the list out of theremaining ones.["source","java",subs="attributes,callouts,macros"]--------------------------------------------------include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-init-allocation-aware-selector]--------------------------------------------------<1> Set an allocation aware node selector that allows to pick a node in thelocal rack if any available, otherwise go to any other node in any rack. Itacts as a preference rather than a strict requirement, given that it goes toanother rack if none of the local nodes are available, rather than returningno nodes in such case which would make the client forcibly revive a local nodewhenever none of the nodes from the preferred rack is available.WARNING: Node selectors that do not consistently select the same set of nodeswill make round-robin behaviour unpredictable and possibly unfair. Thepreference example above is fine as it reasons about availability of nodeswhich already affects the predictability of round-robin. Node selection shouldnot depend on other external factors or round-robin will not work properly.
 |