The Java high-level rest-client docs provide the way to set authentication in the elastic client like this:
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("user", "password"));
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
}
});
However, for my use case, which is for an MVC application, I need to set credentials dynamically, fetching them from REST headers and send the same to ES. I tried to build the client dynamically but it creates several threads and application ran out of memory.
- One of the problems was that I wasn't closing the client after building it dynamically either, hence it created several threads.
- Now, is it recommended to build clients for each REST request, if I close them as well? Will the continuous creation and deletion of thread cause memory/processing usage problem?
- How do you dynamically change the credential after the client is built?
- I did try one approach, which kind of seemed to work:
- I tried fetching the user name and password through a Bean variable inside the setHttpClientConfigCallback method, which could change the username and password per request. However, one running the code, it was using old credentials (blank strings) only, which was set during the application initialization and not taking the latest values from the Bean getter function.
- Can this be fixed by adding
httpClientBuilder.disableAuthCaching();
? I am yet to try this.