Springboot 整合 elasticsearch7

Springboot 整合 elasticsearch

本文为 elasticsearch7.11.2整合

  1. 当 spring-boot-starter-parent 与自己的 es 版本不匹配时,需要单独声明保证兼容性
<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.11.2</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
      <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>7.11.2</version>
      </dependency>
      <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-client</artifactId>
        <version>7.11.2</version>
      </dependency>
    </dependencies>
</dependencyManagement>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
  1. 配置文件

    spring:
      elasticsearch:
        rest:
          uris: http://192.168.31.201:9200,http://192.168.31.202:9200,http://192.168.31.203:9200
    
  2. 配置类

    package com.example.springplayground.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;
    
    import java.util.Arrays;
    
    /**
     * @author zhangfan
     */
    @Configuration
    public class ESConfig {
        @Value("${spring.elasticsearch.rest.uris}")
        private String[] uris;
    
        @Bean
        public RestHighLevelClient restHighLevelClient() {
            final HttpHost[] httpHosts = Arrays.stream(uris).map(HttpHost::create).toArray(HttpHost[]::new);
            return new RestHighLevelClient(RestClient.builder(httpHosts));
        }
    }
    
    
posted @ 2022-02-20 00:24  那个吧..你懂的!  阅读(477)  评论(0编辑  收藏  举报