In general, we can get a Java client in the following way.
123456789 |
Public client gettransportclient () { ///Set Client.transport.sniff to True to enable the client to sniff the entire cluster state and add the IP addresses of other machines in the cluster to the client, The advantage of this is that you do not have to manually set up all the clusters in the cluster IP to the connection client, it will automatically help you to add, and automatically discover the new cluster machine. Settings Settings = Immutablesettings.settingsbuilder (). put (m). Put ("Cluster.name", clustername). Put (" Client.transport.sniff ", true). Build (); Client client = new Transportclient (settings). addtransportaddress (New Inetsockettransportaddress (host, port)); return client; } |
Or the following methods:
123456789 |
Public Client getembeddedclient () { Nodebuilder nodebuilder = new Nodebuilder (); Node node = nodebuilder.loadconfigsettings (False). ClusterName (clustername). Local (true). Node ();// node node = Nodebuilder.loadconfigsettings (False). ClusterName (ClusterName). node (); Client client = Node.client (); return client; } |
This is not a problem in the test environment, but there are problems in the online environment, such as memory overflow and timeout.
It is recommended to obtain a Java client instance using the following method
12345678910111213141516171819202122232425 |
static map<string, string> m = new hashmap<string, string> (); Set Client.transport.sniff to True to enable the client to sniff the entire cluster state, add the IP addresses of other machines in the cluster to the client, and static Settings Settings = Immutablesettings.settingsbuilder (). put (m). Put ("Cluster.name", clustername). Put ("Client.transport.sniff", true). Build (); //Create private object privately static transportclient client; 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 (host, port)); } catch (Exception e) {e.printstacktrace (); }} //Get instance public static synchronized Transportclient gettransportclient () {return client; }
|
The Java client creates a connection pool, so don't close it when you're done, and you can reuse it next time. Using a singleton mode, you can ensure that the application only produces one instance.
Using the Java reflection method to generate a client is significantly more efficient than the new one.
Establishment of the Elasticsearch client