Spring boot 2.5.x整合ElasticSearch 7.1x

語言: CN / TW / HK

本文已參與「新人創作禮」活動,一起開啟掘金創作之路。

一、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官網提供的版本關係圖。

其他依賴:

```

4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.6 org.spring.data elasticsearch 0.0.1-SNAPSHOT elasticsearch Demo project for Spring Boot 11 org.springframework.boot spring-boot-starter

    <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>

```

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 相關依賴:

``` org.springframework.boot spring-boot-starter-test test

org.junit.jupiter junit-jupiter-api test ```

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成功。