springboot集成elasticsearch


版本信息

springboot集成es会有版本要求。
springboot:2.2.6
es:6.4.0

 
        org.springframework.boot
        spring-boot-starter-parent
        2.2.6.RELEASE
         
    

有三种方式:

  • Transport Client,es 7.x 后不再支持
  • 用spring的spring-data-elasticsearch
  • 官网上的high-level-client( https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.4/java-rest-high.html )
    用spring自带的需要注意es版本

百度查得:
Spring Boot更新到2.x版本, 默认spring-boot-starter-data-elasticsearch 默认的ES版本为5.6.9;如果你仍然使用Spring Boot 1.x版本,那么默认的Elastisearch版本为2.x ( https://www.jianshu.com/p/c5c3e834c028 )

spring官网
https://docs.spring.io/spring-data/elasticsearch/docs/3.2.0.RC3/reference/html/#preface.versions

high-level-client

pom添加依赖

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

需要一个 RestClient 的 bean,在application里添加或者用 @Component

public class TiebaApplication {

    public static void main(String[] args) {
        SpringApplication.run(TiebaApplication.class, args);
    }

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

    @Bean
    public ExecutorService pool(){
        ExecutorService pool =  Executors.newFixedThreadPool(10);
        return pool;
    }

}

使用(官网api: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.4/java-rest-high.html )