Recommended HighLevelRestClient configuration for Spring App


Is it a good practice to create HighLevelRestClient as a bean in Spring config and autowire it wherever its needed? like below:

/** Configuration Bean */
public class ElasticsearchConfig {

private String host;

private int port;

public HighLevelRestClient restClient() {
    return RestClient.builder(new HttpHost(host, port)).build();


// use the dependency in your other components/services, using dependency injection
private RestClient restClient;

I am asking this because I am getting Timeouts, if the app is idle for a period & did not make connections to the Elastic Hosts. The subsequent requests goes smoothly.

More details on the issue:

Issue: I was making the RestClient as a Bean managed by Spring container at starup and hoping that all the subsequent request to the app will be able to utilize it. It works fine too, but only until a pause or idle time. What I observed is - if there is a idle time for 20-25 mins the RestClient is loosing the stability. So when the next request comes, the very first times out !!
After that one request, Rest Client comes back into the business and everything goes back to normal.

I may have missed something here but couldn't find how RestClient will continue to maintain the connect with the given hosts? I see documents around Sniffer doing the hearbeats checks though.

So, I am going back to create a fresh rest client for each request coming to my server, until I get something concrete on this. Thanks !!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.