RestHighLevelClient从字面意思理解就是restful风格的高级别的客户端,看一下Elastic官网怎么定义的:
The high-level client will internally create the low-level client used to perform requests based on the provided builder. That low-level client maintains a pool of connections and starts some threads so you should close the high-level client when you are well and truly done with it and it will in turn close the internal low-level client to free those resources. This can be done through the close().
RestHighLevelClient 底层封装的是一个http连接池,当需要执行 update、index、delete操作时,直接从连接池中取出一个连接,然后发送http请求到ElasticSearch服务端,服务端基于Netty接收请求。
新版本的elasticsearch java client 都推荐用RestHighLevelClient去连接ES集群,放弃掉之前的transport client的方式。下面是构建RestHighLevelClient的方法:
protected void buildRestHighLevelClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpHost[] httpHosts = Arrays.stream(elasticSearchHosts.split(",")).map(host -> new HttpHost(host, elasticSearchPort)).filter(Objects::nonNull).toArray(HttpHost[]::new);
RestClientBuilder builder = RestClient.builder(httpHosts)
.setHttpClientConfigCallback(httpClientBuilder -> {
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout);
httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
return httpClientBuilder;
});
restHighLevelClient = new RestHighLevelClient(builder);
}
RestHighLevelClient归根结底也是HttpClient 我们以4.5版本api来说,配置方式:设置在RequestConfig中
RestHighLevelClient可以灵活构建出各种Request对象,这个在这里就不再说具体API的用法了。当然抽象层级越高的东西性能相对差一点,但更能满足企业级开发的需求。
每周一句:奉献和热爱让人生一往无前,方法和勤奋能让你变得优秀,特长和兴趣能让你变得卓越。