The following content is the source codes of the client side.
private Client createClient(String hosts, String cluster) {
logger.info("the elasticsearch host: " + hosts + ", cluster is " + cluster);
Client client = null;
try {
TransportClient build = null;
if(null != cluster && !cluster.trim().isEmpty()) {
Settings settings = Settings.settingsBuilder()
.put("client.transport.sniff", false)
.put("cluster.name", cluster).build();
build = TransportClient.builder().settings(settings).build();
logger.info("initialized the cluster elasticsearch client settings!");
} else {
build = TransportClient.builder().build();
}
String[] hostArr = hosts.split(",");
for(String item : hostArr) {
String[] hps = item.split(":");
String host = "127.0.0.1";
Integer port = 9300;
if(hps.length > 0) {
host = hps[0];
}
if(hps.length > 1) {
port = Integer.parseInt(hps[1]);
}
logger.info("the elasticsearch host is " + host + ", port is " + port);
InetAddress address = null;
String ipExp = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
Pattern pat = Pattern.compile(ipExp);
Matcher matcher = pat.matcher(host);
if (matcher.matches()) {
String[] segs = host.split("\\.");
byte[] bs = new byte[]{Short.valueOf(segs[0]).byteValue(),
Short.valueOf(segs[1]).byteValue(),
Short.valueOf(segs[2]).byteValue(),
Short.valueOf(segs[3]).byteValue()};
address = InetAddress.getByAddress(bs);
} else {
address = InetAddress.getByName(host);
}
build.addTransportAddress(new InetSocketTransportAddress(address, port));
}
client = build;
} catch (UnknownHostException e) {
logger.error("failed to initialize the elasticsearch client with the unknown host!", e);
} catch (Exception e) {
logger.error("failed to initialize the elasticsearch client!", e);
}
return client;
}