- 原因
java操作elasticsearch的博文很多,大多都是复制粘贴,要不就是过时,抄来抄去没啥意思,所以这个系列就简单记录一下。
- elasticsearch单机或集群搭建
此过程略过
- java连接elasticsearch单机
代码如下:
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
//
ElasticsearchTransport transport = new RestClientTransport( restClient, new JacksonJsonpMapper());
//
ElasticsearchClient client = new ElasticsearchClient(transport);
很简单吧,把IP和端口代入即可,具体源码就不展开了
csdn博主: liming10101010原创csdn博主: liming10101010原创
带密码就加一个CredentialsProvider,代码如下:
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(name, pwd));
RestClient restClient = RestClient.builder(new HttpHost("192.168.1.201", 9200, "https"))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
.build();
参数一目了然,是https就在后面加个https即可。
- java连接elasticsearch集群
代码如下:
HttpHost[] httpHosts = {new HttpHost("192.168.1.201", 9200, "https"),
new HttpHost("192.168.1.203", 9200, "https"),
new HttpHost("192.168.1.203", 9200, "https"),};
RestClient restClient = RestClient.builder(httpHosts).build();
是不是很容易,so easy,加上密码如下:
opencv for android(二十三):使用opencv人脸64点位实现人脸装饰物_liming10101010的博客-CSDN博客
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(name, pwd));
HttpHost[] httpHosts = {new HttpHost("192.168.1.201", 9200, "https"),
new HttpHost("192.168.1.203", 9200, "https"),
new HttpHost("192.168.1.203", 9200, "https"),};
RestClient restClient = RestClient.builder(httpHosts)
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
.build();
- 代码封装如下:
public static init(String hosts, String name, String pwd){
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(name, pwd));
HttpHost[] httpHosts = Arrays.stream(hosts.split(",")).map(x -> {
String[] hostInfo = x.split(":");
return new HttpHost(hostInfo[1].replaceAll("//", ""), Integer.parseInt(hostInfo[2]), hostInfo[0]);
}).toArray(HttpHost[]::new);
RestClient restClient = RestClient.builder(httpHosts)
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
.build();
}
使用就主要这样了:
opencv for android(二十四):使用opencv的BackgroundSubtractorKNN动态追踪_liming10101010的博客-CSDN博客文章来源:https://uudwc.com/A/gd0G
String [] hosts = {"192.168.1.200:9200", "192.168.1.201:9200", "192.168.1.202:9200"};
init(hosts, "root", "root");
ok,连接完成文章来源地址https://uudwc.com/A/gd0G