ElasticSearch 集羣連接方法 Java

package com.ctpsp.custominfo.api.configuration;


import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.network.InetAddresses;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.UnknownHostException;

@Configuration
public class ElasticSearchConfiguration {
    @Value("${elastic.esServerIps}")
    private String esServerIps;
    @Value("${elastic.port}")
    private int port;

    private static TransportClient  transPort = null;

    @Bean
    public TransportClient client() throws UnknownHostException {

        try {

            Settings settings = Settings.builder()
                    .put("cluster.name", "leon")
                    .build();

            transPort = new PreBuiltTransportClient(settings);

            String esIps[] = esServerIps.split(",");
            for (String esIp : esIps) {//添加集羣IP列表
                TransportAddress transportAddress =  new InetSocketTransportAddress(
                        InetAddresses.forString(esIp),
                        9300);
                transPort.addTransportAddresses(transportAddress);
            }

            return transPort;
        }catch (Exception e){
            e.printStackTrace();
            if (transPort != null){
                transPort.close();
            }
        }
        return null;
    }

}

properties

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