pom文件配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>x-pack-transport</artifactId>
<version>5.5.0</version>
</dependency>
ElasticsearchTemplate和TransportClient的配置
注意:elastisearch开通了ssl(xpack.security.transport.ssl.enabled: true),如果要用9300端口来通信,是要设置ca证书,和客户端的key和客户端证书,否则无法通过es认证。
@Override
public ElasticsearchTemplate build() {
return new ElasticsearchTemplate(transportClient());
}
private TransportClient transportClient() {
try {
Settings.Builder settings = Settings.builder().put("cluster.name", clusterName);
if(!StringUtil.isEmpty(userPass)&&!userPass.equals("''")){
settings.put("xpack.security.user", userPass);
settings.put("xpack.ssl.certificate_authorities", caCrt);
settings.put("xpack.ssl.key", clientKey);
settings.put("xpack.ssl.certificate", clientCrt);
if (caCrt != null && !StringUtil.isEmpty(caCrt)) {
settings.put("xpack.security.transport.ssl.enabled", "true");
}
}
TransportClient client = new PreBuiltXPackTransportClient(settings.build());
Map<String, Integer> nodeMap = getNodeMap();
for (Map.Entry<String, Integer> entry : nodeMap.entrySet()) {
client.addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName(entry.getKey()), entry.getValue()));
}
return client;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
yml配置文件
spring:
data:
elasticsearch:
action:
auto_create_index: true
cluster-name: jiqunming
cluster-nodes: 192.168.1.1:9300,192.168.1.2:9300,192.168.1.3:9300
index-name: test
xpack:
security:
user: zhanghao:mima
ca-crt: /crt/ca.crt
client-key: /crt/client.key
client-crt: /crt/client.crt
参照官网地址配置:
https://www.elastic.co/guide/en/x-pack/6.2/java-clients.html