(十)、集成SpringBoot
官网: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/index.html
1.ElasticSearch依赖
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.6.2</version> </dependency>
2.初始化ElasticSearch
RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")));
client.close();
3.分析这个类的方法
(1).创建一个空项目
(2).在空项目中创建SpringBOOT模块
选择NoSQL的 es依赖
(3).配置JDK版本
因为我们是新建的空项目所以要用 JDK8 版本
4.配置基本的项目
问题: 一定要保证我们的导入的依赖和我们的E下载ES版本一致。
我们本地的版本是 7.6.2.
(1).解决版本不一致问题
如果我们在构想项目的时候自己选用默认的版本我们就需要 自定义版本依赖。否则不需要自定义版本的依赖了。
<!-- 自己定义es版本依赖,保证和本地一致 --> <elasticsearch.version>7.6.2</elasticsearch.version>
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.jsxs</groupId> <artifactId>Jsxs-es-api-01</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Jsxs-es-api-01</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <!-- 自己定义es版本依赖,保证和本地一致 --> <elasticsearch.version>7.6.2</elasticsearch.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <version>2.7.9</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
(2).配置配置类文件
package com.jsxs.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @Author Jsxs * @Date 2023/6/27 11:21 * @PackageName:com.jsxs.config * @ClassName: ElasticSearchClientConfig * @Description: TODO * @Version 1.0 */ @Configuration public class ElasticSearchClientConfig { @Bean public RestHighLevelClient restHighLevelClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"))); return client; } }