Spring boot 2.5.x整合ElasticSearch 7.1x

3,129 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

一、ElasticSearch介绍

        ElasticSearch是一个分布式搜索引擎,能与SpringBoot、Python等框架做集成 , 可扩展性好。 另外elaticsearch官方提供了可视化的图表工具kibana, 能够让您的搜索数据展示的更友好,ElasticSearch提供一系列Rest API给客户端索引,  他能够对海量数据下的指定搜索能快速的做出响应。

        官网说明:  ElasticSearch是一个基于JSON的分布式搜索和分析引擎。

        Spring官网提供了spring data elasticsearch工具包供开发者使用,用SpringBoot开发时,我们一定要注意Springboot版本与ElasticSearch版本对应关系,如果版本对不上,在调用时,可能会发生问题。

elasticsearch与springboot版本对应关系

注:  在ElasticSearch 7以后,Spring data建议采用High-level REST client。 

二、Spring Boot 整合ElasticSearch

         通过版本关系图,我们需要准备Springboot版本与elasticsearch客户端,我们就使用图中最第一条,即最新版本。

1. SpringBoot版本

        Spring Boot 版本采用2.5.6, 可以在2.5.x中选一个即可。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.6</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

data-elasticsearch不用指定版本,因为是依赖Springboot,Springboot包下载好后,会自定给你指定data-elasticsearch的版本:

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

         如上图,maven会自动给你下载4.2.6版本的包,正好也符合Spring官网提供的版本关系图。

其他依赖:

<?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.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.spring.data</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elasticsearch</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <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>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>



        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>


        <!-- springboot test-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>


        <!--整合elasticsearch-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. ElasticSearch服务器版本 

        Spring官网推荐的版本是7.15.2, 在这里推荐一个国内加速下载网站,华为云,地址如下:

Index of elasticsearch-local

下载64位版本: 

​ 

注: 解压的目录不要放到program files目录下,因为低版本的elasticsearch运行时可能会出现没有权限写入的问题。

解压后到E盘后,启动elasticsearch服务器, 以管理员的身份进行运行:

 如果能看到红框框里的内容,说明就启动成功了。

三、调用ElasticSearch

1. 配置elasticSearch客户端

        刚提到Spring官网在elasticsearch 7以后,推荐我们使用high-leve-client,那我们就使用RestHighLevelClient。

        添加配置类ElasticSearchClientConfig,  可将uri放入到配置文件里,为了方便测试,在这里写固定 http://localhost:9200。

package org.spring.data.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {

    @Value("${spring.elasticsearch.rest.uris}")
    private String urls;


    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost",9200, "http")
                )
        );
        return restHighLevelClient;
    }
}

 spring.elasticsearch.rest.uris=http://localhost:9200

2. RestFul API使用

首先引入Springboot test 相关依赖:

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
</dependency>
     

<dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
</dependency>

Spring data ElasticSearch提供了的增、删、改、查的包装类, 分别是CreateIndexRequest、DeleteIndexRequest、GetIndexRequest、UpdateRequest,另外不推荐使用过时的API,例如: 

 @Deprecated
    public boolean exists(org.elasticsearch.action.admin.indices.get.GetIndexRequest request, RequestOptions options) throws IOException {
        return (Boolean)this.restHighLevelClient.performRequest(request, IndicesRequestConverters::indicesExist, options, RestHighLevelClient::convertExistsResponse, Collections.emptySet());
    }

可以从导包来查看是否过时:org.elasticsearch.action.admin.indices.get, 推荐使用的GetIndexRequest是在org.elasticsearch.client.indices包下。

package org.spring.data;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.elasticsearch.client.RequestOptions;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

@SpringBootTest(classes = ElasticsearchApplication.class)
public class ElasticsearchApplicationTests {

    @Test
    void contextLoads() {
    }


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * create
     * @throws IOException
     */
    @Test
    public void testCreateIndex() throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("test");
        CreateIndexResponse response = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * exist
     *
     * @throws IOException
     */
    @Test
    public void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("test");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     *  delete
     */
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

}

 如果都测试成功,那么表示连上了elasticsearch, Spring boot整合elasticsearch成功。