package com.zhiweidata.bjfzxWebapp.esDao;

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

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 com.zhiwei.es.util.ESIndexesUtil;
import com.zhiwei.es.util.ESIndexesUtil.ESIndexes;
import com.zhiweidata.bjfzxWebapp.conf.EsConfig;

public class ESClient
{
//    private static String esIp = "106.14.249.240";
//    private static String esIp = "192.168.0.99";
//    private static int esPort = 9300;
//    private static String clusterName = "es_zwjrqb";
//    private static String clusterName = "es";
    private static String clusterName = "Media-University";
    
    /**
     * 索引工具
     */
    public static ESIndexes eSIndexes = ESIndexesUtil.create(EsConfig.es_ip1, 9200);
    
    private static class ESClientHolder{
        
        static TransportClient client = initESClient();
        private static TransportClient initESClient()
        {
            Settings esSettings = Settings.builder()

                    .put("cluster.name", clusterName) //设置ES实例的名称

                    .put("client.transport.sniff", false) //自动嗅探整个集群的状态，把集群中其他ES节点的ip添加到本地的客户端列表中

                    .build();
            TransportClient client = new PreBuiltTransportClient(esSettings);
            //此步骤添加IP，至少一个，其实一个就够了，因为添加了自动嗅探配置
            try
            {
                client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(EsConfig.es_ip1), EsConfig.esPort));
            }
            catch (UnknownHostException e)
            {
                e.printStackTrace();
            }
            
            return client;
        }
    }
    public TransportClient getInstance()
    {
        return ESClientHolder.client;
    }
}
