public
Last active

factory for getting ES client

  • Download Gist
TransportClientFactory.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
package com.foo.search;
 
import org.apache.log4j.Logger;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.collect.ImmutableList;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
 
import java.util.Map;
 
public class TransportClientFactory {
 
private static final Logger log = Logger.getLogger(TransportClientFactory.class);
 
private Map<String, String> settings;
private String clientTransportHost;
private Integer clientTransportPort;
private boolean disabled = false;
 
public TransportClientFactory(Map<String, String> settings,
String clientTransportHost,
Integer clientTransportPort,
boolean disabled) {
this.settings = settings;
this.clientTransportHost = clientTransportHost;
this.clientTransportPort = clientTransportPort;
this.disabled = disabled;
}
 
public TransportClient getClient() throws ElasticSearchUnavailableException {
if (this.disabled) {
throw new ElasticSearchUnavailableException("ES is disabled. Check 'es.disable' property");
}
log.info("getting client");
Settings s = ImmutableSettings.settingsBuilder()
.put(this.settings)
.build();
TransportClient client = new TransportClient(s);
client.addTransportAddress(new InetSocketTransportAddress(
this.clientTransportHost,
this.clientTransportPort)
);
 
verifyConnection(client);
return client;
}
 
private void verifyConnection(TransportClient client) {
ImmutableList<DiscoveryNode> nodes = client.connectedNodes();
if (nodes.isEmpty()) {
throw new ElasticSearchUnavailableException("No nodes available. Verify ES is running!");
} else {
log.info("connected to nodes: " + nodes.toString());
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.