Springboot 整合 elasticsearch7


Springboot 整合 elasticsearch

本文为 elasticsearch7.11.2整合

  1. 当 spring-boot-starter-parent 与自己的 es 版本不匹配时,需要单独声明保证兼容性

    
      
        org.elasticsearch.client
        elasticsearch-rest-high-level-client
        7.11.2
      
      
      
        org.elasticsearch
        elasticsearch
        7.11.2
      
      
        org.elasticsearch.client
        elasticsearch-rest-client
        7.11.2
      
    


    org.elasticsearch.client
    elasticsearch-rest-high-level-client

  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));
        }
    }