当前位置 : 主页 > 编程语言 > c++ >

spring-boot 集成elasticsearch5.x配置TransportClient和RestClient

来源:互联网 收集:自由互联 发布时间:2021-06-30
EsConfig.java package com.wd.tools.estools.config;import org.elasticsearch.client.transport.TransportClient;import org.elasticsearch.common.settings.Settings;import org.elasticsearch.common.transport.InetSocketTransportAddress;import org.el
EsConfig.java
package com.wd.tools.estools.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by DimonHo on 2017/10/30.
 */
@Component
@Configuration
public class EsConfig implements FactoryBean
 
  , InitializingBean, DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(EsConfig.class);

    @Value("${spring.data.elasticsearch.cluster-nodes}")
    private String clusterNodes ;

    @Value("${spring.data.elasticsearch.cluster-name}")
    private String clusterName;

    private TransportClient client;


    @Override
    public void destroy() throws Exception {
        try {
            logger.info("Closing elasticSearch client");
            if (client != null) {
                client.close();
            }
        } catch (final Exception e) {
            logger.error("Error closing ElasticSearch client: ", e);
        }
    }

    @Override
    public TransportClient getObject() throws Exception {
        return client;
    }

    @Override
    public Class
   getObjectType() {
        return TransportClient.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        buildClient();
    }

    protected void buildClient()  {
        try {
            PreBuiltTransportClient  preBuiltTransportClient = new PreBuiltTransportClient(settings());
            if (!"".equals(clusterNodes)){
                for (String nodes:clusterNodes.split(",")) {
                    String InetSocket [] = nodes.split(":");
                    String  Address = InetSocket[0];
                    Integer  port = Integer.valueOf(InetSocket[1]);
                    preBuiltTransportClient.addTransportAddress(new
                            InetSocketTransportAddress(InetAddress.getByName(Address),port ));
                }
                client = preBuiltTransportClient;
            }
        } catch (UnknownHostException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 初始化默认的client
     */
    private Settings settings(){
        Settings settings = Settings.builder()
                .put("cluster.name",clusterName)
                .put("client.transport.sniff",true)
        .build();
        client = new PreBuiltTransportClient(settings);
        return settings;
    }
}
 
QueryService.java
package com.wd.tools.estools.service;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collections;

/**
 * Created by DimonHo on 2017/10/30.
 */
@Service
public class QueryService {

    @Autowired
    private TransportClient client;

    @Autowired
    private RestClient restClient;

    public SearchResponse getAllData(){
        SearchResponse response = client.prepareSearch("journal_navication5.0").setTypes("titles").setQuery(QueryBuilders.matchAllQuery()).get();
        return response;
    }

    public Response getAllDataForRestClient(){
        String url = "/journal_navication5.0/titles/_search";
        HttpEntity params = new NStringEntity("{\"query\":{\"match_all\":{}}}",
                ContentType.APPLICATION_JSON);
        try {
            return restClient.performRequest("GET", url, Collections.
 
  emptyMap(), params);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
 
application.yml
spring:
  data:
    elasticsearch:
      cluster-nodes: 192.168.1.75:9300,192.168.1.76:9300,192.168.1.77:9300,192.168.1.78:9300
      cluster-name: wdkj_test


elasticsearch:
  rest:
    client:
      cluster-nodes: 192.168.1.75:9200,192.168.1.76:9200,192.168.1.77:9200,192.168.1.78:9200
QueryController.java
package com.wd.tools.estools.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wd.tools.estools.service.QueryService;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * Created by DimonHo on 2017/10/30.
 */
@RestController
public class QueryController {

    @Autowired
    QueryService queryService;

    @GetMapping("/findAll")
    public String findAll() throws IOException {
        return queryService.getAllData().toString();
    }

    @GetMapping("/getAllDataForRestClient")
    public JSONObject getAllDataForRestClient() throws IOException {
        JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(queryService.getAllDataForRestClient().getEntity(),"utf-8"));
        return jsonObject;
    }
}
RestEsConfig.java
package com.wd.tools.estools.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by DimonHo on 2017/10/30.
 */
@Component
@Configuration
@ConfigurationProperties(prefix = "elasticsearch.rest.client")
public class RestEsConfig {

    private static final Logger logger = LoggerFactory.getLogger(RestEsConfig.class);

    private String clusterNodes ;

    private RestClient restClient;

    public String getClusterNodes() {
        return clusterNodes;
    }

    public void setClusterNodes(String clusterNodes) {
        this.clusterNodes = clusterNodes;
    }

    public void destroy() throws Exception {
        try {
            logger.info("Closing elasticSearch client");
            if (restClient != null) {
                restClient.close();
            }
        } catch (final Exception e) {
            logger.error("连接关闭失败{}",e);
        }
    }

    @Bean
    public RestClient creatClient() throws Exception {
       return buildClient();
    }

    protected RestClient buildClient()  {
        if (!"".equals(clusterNodes)) {
            String[] nodes = clusterNodes.split(",");
            HttpHost[] httpHosts = new HttpHost[nodes.length];
            for (int i = 0; i < nodes.length; i++) {
                String InetSocket[] = nodes[i].split(":");
                String Address = InetSocket[0];
                Integer port = Integer.valueOf(InetSocket[1]);
                httpHosts[i] = new HttpHost(Address, port, "http");
            }
            restClient = RestClient.builder(httpHosts).build();
        }
        return restClient;
    }

}
pom.xml
 

 
	
  
   4.0.0
  

	
  
   com.wd.tools
  
	
  
   es-tools
  
	
  
   0.0.1-SNAPSHOT
  
	
  
   jar
  

	
  
   es-tools
  
	
  
   Demo project for Spring Boot
  

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

	
   
   
    2.9.1
    
   
    2.9.1
    
   
    5.5.1
    
   
    UTF-8
    
   
    UTF-8
    
   
    1.8
    
  

	
   
    
    
    
     org.apache.logging.log4j
     
    
     log4j-api
     
    
     ${log4j-api.version}
     
    
    
    
     org.apache.logging.log4j
     
    
     log4j-core
     
    
     ${log4j-core.version}
     
    
    
    
     org.elasticsearch
     
    
     elasticsearch
     
    
     ${elasticsearch.version}
     
    
    
    
     org.elasticsearch.client
     
    
     transport
     
    
     ${elasticsearch.version}
     
    
    
    
     org.elasticsearch.client
     
    
     rest
     
    
     ${elasticsearch.version}
     
    
    
    
    
    
     com.alibaba
     
    
     fastjson
     
    
     1.1.41
     
    
    
    
     org.springframework.boot
     
    
     spring-boot-starter-web
     
    
    
    
     org.springframework.boot
     
    
     spring-boot-starter-test
     
    
     test
     
    
    
    
     org.springframework.boot
     
    
     spring-boot-configuration-processor
     
    
     true
     
    
  

	
   
    
     
     
      org.springframework.boot
      
     
      spring-boot-maven-plugin
      
     
    
  



 
网友评论