**学习笔记(ElasticSearch)–java客户端连接腾讯云ElasticSearch
(纪念这次踩的坑)
近日,在腾讯云上免费购置了一台ElasticSearch实例拿来学习。发现一个重大问题:java客户端Restful API怎么也连不上腾讯云的elsaticsearch实例,各种教程也找了,客服也问了还是失败了。
现在问题总算解决了。
这是springboot集成ES的配置类
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchConfig {
//配置elasticsearch客户端
@Bean
public RestHighLevelClient restHighLevelClient(){
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username","password"));
RestClientBuilder builder = RestClient.builder(
new HttpHost("公网地址(去掉https://)", 9200,"https"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
return new RestHighLevelClient(builder);
}
}
原因是腾讯默认不开放外网访问ES集群,而且默认是https连接,且需要输入用户名和密码进行权限认证。
现在来回顾一下如何访问腾讯云es实例。
步骤
第一步:先重置一下默认elastic用户名的密码
第二步:申请公网,并添加公网ip地址进白名单。(本地ip地址可以通过百度ip地址获得)
第三步:复制公网地址,创建es配置类(参考第一张图),即可访问es实例
成功之后查询日志可以发现有以下输出
水平有限,希望友友们多多指导