Elasticsearch高級API-----獲得客戶端對象

 我用的環境是ES7.1.1、jdk1.8、gradle、springboot1.5.1

  • 引入高級api的jar包

compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.1.1'
compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-client', version: '7.1.1'
  •  springboot環境包

 

testCompile group: 'junit', name: 'junit', version: '4.12'

compile ("org.springframework.boot:spring-boot-starter:1.5.1.RELEASE")
compile ('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.2.0')
compile ('mysql:mysql-connector-java:5.1.38')//驅動
compile group: 'com.zaxxer', name: 'HikariCP', version: '3.3.1'//連接池
compile fileTree(dir:'lib',include:['*.jar'])//這裏是es裏的lib
  •  將client納入spring環境

package com.yuqi.esclient;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestClientBuilder builder = RestClient.builder(new HttpHost("127.0.0.1", 9200));
        return new RestHighLevelClient(builder);
    }
}
  • 使用

 

package com.yuqi.server;

import com.yuqi.mapper.CarriskalarmMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class DiServier implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(DiServier.class);

    @Autowired
    RestHighLevelClient client;

    @Override
    public void run(String... args) throws Exception {

          //TODO  在這裏直接使用上面注入的client

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章