package com.zhiwei.finance;

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.util.Config;

/**
 * es连接类
 * 
 * @author shenjinzhu
 *
 */
public class ESClient {
	private static String esIp;
	private static int esPort;
	private static String clusterName;

	
	private static class ESClientHolder {
		
		static TransportClient client = initESClient();
		private static TransportClient initESClient() {
			esIp=Config.getVal("esIp");
			clusterName=Config.getVal("clusterName");
			esPort=Integer.valueOf(Config.getVal("esPort"));
			Settings esSettings = Settings.builder().put("cluster.name", clusterName) // 设置ES实例的名称
					// 自动嗅探整个集群的状态，把集群中其他ES节点的ip添加到本地的客户端列表中
					.put("client.transport.sniff", false).build();
			TransportClient client = new PreBuiltTransportClient(esSettings);
			try {
				client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esIp), esPort));
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
			return client;
		}
	}

	public static TransportClient getInstance() {
		return ESClientHolder.client;
	}

}
