packagecom.xinxin.learning.elasticsearch.config;
importorg.apache.http.HttpHost;
importorg.apache.http.auth.AuthScope;
importorg.apache.http.auth.UsernamePasswordCredentials;
importorg.apache.http.client.CredentialsProvider;
importorg.apache.http.impl.client.BasicCredentialsProvider;
importorg.apache.http.impl.nio.client.HttpAsyncClientBuilder;
importorg.elasticsearch.client.RestClient;
importorg.elasticsearch.client.RestClientBuilder;
importorg.elasticsearch.client.RestHighLevelClient;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
@ConfigurationpublicclassElasticsearchConfiguration {
@Value("${elasticsearch.hosts}")
privateStringhosts;
@Value("${elasticsearch.userName}")
privateStringuserName;
@Value("${elasticsearch.password}")
privateStringpassword;
@BeanpublicRestHighLevelClientrestHighLevelClient() {
String[] hosts=this.hosts.split(",");
HttpHost[] httpHosts=newHttpHost[hosts.length];
for (inti=0; i<hosts.length; i++) {
httpHosts[i] =newHttpHost(
hosts[i].split(":")[0],
Integer.parseInt(hosts[i].split(":")[1]),
"http");
}
finalCredentialsProvidercredentialsProvider=newBasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, newUsernamePasswordCredentials(userName, password));
RestClientBuilderbuilder=RestClient.builder(httpHosts).setRequestConfigCallback(newRestClientBuilder.RequestConfigCallback() {
@OverridepublicRequestConfig.BuildercustomizeRequestConfig(RequestConfig.BuilderrequestConfigBuilder) {
requestConfigBuilder.setConnectTimeout(-1);
requestConfigBuilder.setSocketTimeout(-1);
requestConfigBuilder.setConnectionRequestTimeout(-1);
returnrequestConfigBuilder;
}
}).setHttpClientConfigCallback(newRestClientBuilder.HttpClientConfigCallback() {
@OverridepublicHttpAsyncClientBuildercustomizeHttpClient(HttpAsyncClientBuilderhttpClientBuilder) {
httpClientBuilder.disableAuthCaching();
returnhttpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
RestHighLevelClientclient=newRestHighLevelClient(builder);
returnclient;
}
}