本节主要讲解Java Elasticsearch RestHighLevelClient的配置详解。
RestHighLevelClient常用配置如下:
- elasticsearch连接地址
- elasticsearch账号/密码
- Http请求头
- 连接超时
- 设置线程池大小
创建client
RestHighLevelClient 依赖 REST low-level client builder 进行配置,即依赖底层的RestClientBuilder对象进行参数设置
// 首先创建RestClientBuilder,后续章节通过RestClientBuilder对象进行参数配置。
RestClientBuilder restClientBuilder = RestClient.builder(
new HttpHost("localhost", 9200, "http"), // 设置ES服务地址,支持多个
new HttpHost("localhost", 9201, "http"));
// 创建RestHighLevelClient,请求都是通过RestHighLevelClient实例发出去的。
RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
配置ES账号密码
restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
// 通过CredentialsProvider实例,配置账号和密码
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("user", "password"));
// 设置安全验证凭证
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
设置Http Header
// 创建header数组,可以设置多个header
Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")};
// 设置http header
restClientBuilder.setDefaultHeaders(defaultHeaders);
Timeout设置
配置Elasticsearch连接超时时间
restClientBuilder.setRequestConfigCallback(
new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(
RequestConfig.Builder requestConfigBuilder) {
return requestConfigBuilder
.setConnectTimeout(5000) // 设置连接超时时间,5秒
.setSocketTimeout(60000); // 设置请求超时时间,1分种
}
});
设置线程池大小
restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultIOReactorConfig(
IOReactorConfig.custom()
.setIoThreadCount(10) // 设置线程数
.build());
}
});