spring boot 整合elastic search 5.x

来源:互联网 发布:香港保险 知乎 编辑:程序博客网 时间:2024/06/07 05:15

spring boot 整合elasticsearch 可以使用spring-data-elasticsearch。使用spring-data-elasticsearch,不过最高只支持elasticsearch2.4.4。pom.xml配置如下:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>


对于elasticsearch 5.x版本,因为没有对应版本的spring-data-elasticsearch,所以只能将elasticsearch的客户端对象注入到spring中,pom.xml配置如下:

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.2.2</version>
</dependency>


<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.2.2</version>
</dependency>


<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>


属性文件:



配置类:

@Component
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSearchConfig {
private String clusterName;


private String clusterNodes;


public String getClusterName() {
return clusterName;
}


public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}


public String getClusterNodes() {
return clusterNodes;
}


public void setClusterNodes(String clusterNodes) {
this.clusterNodes = clusterNodes;
}


@Bean
public Client getESClient() {
// 设置集群名字
Settings settings = Settings.builder().put("cluster.name", this.clusterName).build();
Client client = new PreBuiltTransportClient(settings);


try {
// 读取的ip列表是以逗号分隔的
for (String clusterNode : this.clusterNodes.split(",")) {
String ip = clusterNode.split(":")[0];
String port = clusterNode.split(":")[1];
((TransportClient) client).addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName(ip), Integer.parseInt(port)));
}
} catch (UnknownHostException e) {
e.printStackTrace();
}


return client;
}
}


使用:




0 2
原创粉丝点击