Created
November 14, 2011 18:48
-
-
Save thesurlydev/1364734 to your computer and use it in GitHub Desktop.
factory for getting ES client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment