pom文件 注意自己的elasticsearch服务端版本 下面的方式只在6.8.0版本测试过
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.11</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>x-pack-transport</artifactId>
<version>6.8.11</version>
</dependency>
配置类
@Configuration
public class ElasticsearchConfig {
//连接信息改成自己的
private String clusterName = "elasticsearch";
private String clusterNodes = "127.0.0.1";
//用户名:密码
private String clusterPassword = "elastic:123456";
@Bean
public Client client() throws Exception {
@SuppressWarnings("resource")
Client client = new PreBuiltXPackTransportClient(Settings.builder()
.put("cluster.name", clusterName)
.put("xpack.security.user", clusterPassword)
.build())
.addTransportAddress(new TransportAddress(InetAddress.getByName(clusterNodes), 9300));
return client;
}
@Bean(name = "elasticsearchTemplate")
public ElasticsearchTemplate elasticsearchTemplate() throws Exception {
ElasticsearchTemplate elasticsearchTemplate;
try {
elasticsearchTemplate = new ElasticsearchTemplate(client());
return elasticsearchTemplate;
} catch (Exception e) {
e.printStackTrace();
return new ElasticsearchTemplate(client());
}
}
}