一、安装部署

安装Elasticsearch 7.6.2的部署文档,参考:https://cloud.tencent.com/developer/article/1804215

开启xpack,参考:

https://segmentfault.com/a/1190000022102940

https://cloud.tencent.com/developer/article/1772919

开启后,可执行 curl 命令测试:

1
curl --user elastic:xxxx -XGET 'http://es_ip:9200'

二、Java 客户端初始化

https://www.elastic.co/guide/en/elasticsearch/reference/7.6/java-clients.html#java-clients(不推荐使用)

明文密码认证:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/_basic_authentication.html

1、明文密码认证方式

pom 依赖:

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.6.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>

客户端初始化示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private RestHighLevelClient client = null;

private void buildClient() throws NumberFormatException {
String hostAndPorts = "localhost:9200";
String clientSchema = "http";
String clusterUserName = "admin";
String clusterUserPwd = "admin";
String[] array = hostAndPorts.split(",");
HttpHost[] httpHosts = new HttpHost[array.length];
for (int i = 0; i < array.length; i++) {
String hp = array[i];
if (StringUtils.isNotBlank(hp)) {
String[] hostAndPort = hp.split(":");
if (StringUtils.isNotBlank(hostAndPort[0]) && StringUtils.isNotBlank(hostAndPort[1])) {
httpHosts[i] = new HttpHost(new HttpHost(hostAndPort[0], Integer.parseInt(hostAndPort[1]), clientSchema));
}
}
}

CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(clusterUserName, clusterUserPwd));
RestClientBuilder builder = RestClient.builder(httpHosts).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});

// 创建客户端对象 es version 7.6
client = new RestHighLevelClient(builder);
}

2、证书认证方式

证书认证:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/_encrypted_communication.html#_encrypted_communication

待研究补充。。