
import java.net.InetAddress;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
/**
* ES连接类
* @author zxy
*
*/
public class ES_DbUtil {
public static TransportClient transportClient=null; //句柄
public static String esClusterName; //集群名
public static String esServerIps; //集群服务ip集合
public static Integer esServerPort; //Es集群端口
@SuppressWarnings({ "resource", "unchecked" })
public static TransportClient getTransPortClient(String esClusterNam,String esServerIp,Integer esServerPor){
//连接ES transportClient获得句柄
esClusterName = esClusterNam; // 集群名
esServerIps = esServerIp; // 集群服务ip
esServerPort = esServerPor; // Es集群端口
try {
if (transportClient == null) {
if (esServerIps == null || "".equals(esServerIps.trim()))
return null;
Settings esSetting = Settings.builder().put("client.transport.ignore_cluster_name", true)
.put("cluster.name", esClusterName) // 集群名
.put("client.transport.sniff", true) // 自动嗅探,把机器添加到列表
.put("client.transport.ping_timeout", "10s")
.build();
transportClient = new PreBuiltTransportClient(esSetting).addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName(esServerIps), esServerPort));
System.out.println("connectok");
return transportClient;
} else{
System.out.println("hell11");
return transportClient;
}
} catch (Exception e) {
e.printStackTrace();
if (transportClient != null)
transportClient.close();
System.out.println("hellk");
return null;
}
}
public static void clientClose() {
/* 关闭连接 */
if (null != transportClient) {
try {
transportClient.close();
} catch (Exception e) {
}
}
}
}