五、elasticsearch與springboot的集成

版本對應關係java

elasticsearch:5.6.0node

springboot:1.5.6spring

es依賴配置

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <elasticsearch.version>5.6.0</elasticsearch.version>
 </properties>

 <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version><!-- 版本號要 <= 2.7 -->

 </dependency>

 

es配置

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.Configuration;

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

/**
 * @author WangXH
 * @version V1.0
 * @Package com.wangxh.elasticsearch.esstudy.config
 * @date 2017-09-18 2017-9-18 13:29
 * @Description: ElasticSearch  5.6  配置
 */
@Configuration
public class ElasticSearchConfig implements FactoryBean<TransportClient>, InitializingBean, DisposableBean {

    private Logger logger= LoggerFactory.getLogger(this.getClass());

    //因爲項目從2.2.4配置的升級到 5.4.1版本 原配置文件不想動仍是指定原來配置參數
    @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<TransportClient> getObjectType() {
        return TransportClient.class;
    }

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

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info(clusterName+"   "+clusterNodes);
        this.initClient();
    }

    private void initClient()  {
        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;
    }
}

在application.yml文件中配置es的鏈接信息:apache

spring:
  data:
    elasticsearch:
      cluster-name: es-test
      cluster-nodes: 192.168.1.126:9300

9300是es的默認socket端口號,若是配置了多個es的slave,這裏的cluster-nodes 其實也只用配置master的ip:port就能夠,由於在配置中有:client.transport.sniff,true。springboot

 

總結:在集成es到springboot的步驟有如下幾點app

  1. 添加es的依賴以及es的日誌依賴
  2. 建立一個es的配置文件讀取es鏈接配置,並初始化TransportClient
相關文章
相關標籤/搜索