1.1. 集成方式
Spring Boot中集成Elasticsearch有4种方式:
-
REST Client
-
Jest
-
Spring Data
-
Spring Data Elasticsearch Repositories
本文用后面两种方式来分别连接并操作Elasticsearch
1.2. 环境与配置
服务端:elasticsearch-6.3.2 1台
客户端:elasticsearch 6.4.1
服务端配置文件:elasticsearch.yml
cluster.name: my-application
network.host: 192.168.1.134
http.port: 9200
/etc/security/limits.conf
cheng soft nofile 65536
cheng hard nofile 65536
/etc/sysctl.conf
vm.max_map_count=262144
1.3. 版本
Spring Boot 2.0.5默认的elasticsearch版本很低,这里我们用最新版本6.4.1
如果启动过程中出现
java.lang.NoClassDefFoundError: org/elasticsearch/common/transport/InetSocketTransportAddress
则说明,elasticsearch依赖的jar包版本不一致,统一改成6.4.1即可
另外,Spring Boot 2.0.5依赖的spring-data-elasticsearch版本是3.0.1,需要升级到3.1.0
2. 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cjs.example</groupId>
<artifactId>cjs-elasticsearch-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>cjs-elasticsearch-example</name>
<description></description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<elasticsearch.version>6.4.1</elasticsearch.version>
<spring.data.elasticsearch.version>3.1.0.RELEASE</spring.data.elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</depen