Package Cn.test;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;public class Elktest {//private static final String Cluster_Name = "Cluster_Name"; public static final String cluster_name = "Elasticsearch"; Instance name//private static final String IP = "127.0.0.1"; private static final String IP = "192.168.0.29"; private static final int PORT = 9200; Port//1. Set Cluster Name: Default is Elasticsearch, and set Client.transport.sniff to True to allow clients to sniff the entire cluster state, add other machine IPs in the cluster to the client/*//to ES1.6 valid private static Settings Settings = Immutablesettings. Settingsbuilder (). Put ("Cluster.name", CL Uster_name). Put ("Client.transport.sniff", true). Build (); *///For ES2.0 valid private static Settings Settings = Settings. Settingsbuilder () . put ("Cluster.name", cluster_name). Put ("Client.transport.sniff", true). Build (); Private static Transportclient client is created; The reflection mechanism creates a singleton Transportclient object ES1.6 Version//static {//try {//class<?> Clazz = Class.forName (TransportClient.class.getName ()); constructor<?> Constructor = Clazz.getdeclaredconstructor (Settings.class); Constructor.setaccessible (TRUE); Client = (transportclient) constructor.newinstance (settings); Client.addtransportaddress (New Inetsockettransportaddress (Inetaddress.getbyname (IP), PORT)); } catch (Exception e) {//E.printstacktrace (); }//}//es2.0 version Static {try {client = Transportclient.builder (). setting s (settings). Build (). Addtransportaddress (New Inetsockettransportaddress (Inetaddress.getbyname (IP), PO RT)); } CATCH (unknownhostexception e) {e.printstacktrace (); }}//Get instance public static synchronized Transportclient gettransportclient () {return client; }//Add a new node to the cluster public static synchronized void AddNode (String name) {try {Client.addtra Nsportaddress (New Inetsockettransportaddress (Inetaddress.getbyname (name), 9300)); } catch (Unknownhostexception e) {e.printstacktrace (); }}//delete a node in the cluster public static synchronized void RemoveNode (String name) {try {CLI Ent.removetransportaddress (New Inetsockettransportaddress (Inetaddress.getbyname (name), 9300)); } catch (Unknownhostexception e) {e.printstacktrace (); }} public static void Main (String args[]) {gettransportclient (); } }
Java Connection Elasticsearch Cluster