I have a question about the relationships between High Level REST Client
and spring-data-elasticsearch
.
In my spring-boot project, I created the RestClientConfig
for the connection,
// Config file
@Configuration
@EnableElasticsearchAuditing
public class RestClientConfig extends AbstractElasticsearchConfiguration {
@Value("${spring.data.elasticsearch.client.reactive.endpoints}")
private String endpoint;
@Value("${spring.data.elasticsearch.client.reactive.username}")
private String username;
@Value("${spring.data.elasticsearch.client.reactive.password}")
private String pwd;
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(endpoint)
.withBasicAuth(username, pwd)
.build();
return RestClients.create(clientConfiguration).rest();
}
}
and using ElasticSearchRepository
to send some requests to the cluster.
// repository
public interface TestRepository extends ElasticsearchRepository<Test, String> {
}
// I use the repository for whole request to the elasticsearch cluster
testRepo.save(/* object */)
Of course it works well, however, I'm really curious about when the client closed. (As I know, I should close the rest-client when I finished the job. do I have to close it by myself?(if so, when?) or the spring-data-elasticsearch
do it for me?)
Could you please let me know how it works? Any links for codes or documents will be tremendously thankful because I couldn't find any.
Thank you!
Spring Data Elasticsearch never closes the client as it does not create it, you create it in your configuraiton.
And like the linked document states:
you should close the high-level client when you are well and truly done with it
Spring Data Elasticsearch cannot know if and when your application does not need the connection to Elasticsearch any more.
So you might keep a reference to the client and close it if you think you really don't need it. But any calls to ElasticsearchOperations or repositories will fail after that.
Actually I never heard of a problem because of wasted resources of a single instance of this class in an application, I'd say don't bother with closing it.