如果elasticsearch在单一模式下运行,我可以使用以下代码轻松建立RestHighLevel连接:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
但是如果我的弹性集群有3台计算机,例如“ host1”,“ host2”,“ host3”,那么如何在集群模式下创建其余的高级客户端?
谢谢
答案 0 :(得分:0)
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("host1", 9200, "http"),
new HttpHost("host2", 9200, "http"),
new HttpHost("host2", 9200, "http")
)
);
作为doc it looks like you were referencing states,RestClient.builder接受要连接的HttpHosts数组。客户端(实际上是ES低级REST客户端)将向这些主机轮询请求。另请参见Javadoc。
答案 1 :(得分:0)
根据Elasticsearch docs,您可以在RestClient.builder()
中传递多个Elasticsearch主机。
更好的解决方案是从配置中加载Elasticsearch主机(在基于Scala的应用程序中为application.conf
),而不是在代码库中对其进行硬编码。
这是使用Java Varargs(:_*)
的基于Scala的解决方案。
application.conf
es_hosts = ["x.x.x.x","x.x.x.x","x.x.x.x"] // You can even use service-name/service-discovery
es_port = 9200
es_scheme = "http"
代码段
import collection.JavaConverters._
import com.typesafe.config.ConfigFactory
import org.apache.http.HttpHost
import org.elasticsearch.client.{RestClient, RestHighLevelClient}
val config = ConfigFactory.load()
val port = config.getInt(ES_PORT)
val scheme = config.getString(ES_SCHEME)
val es_hosts = config.getStringList(ES_HOSTS).asScala
val httpHosts = es_hosts.map(host => new HttpHost(host, port, scheme))
val low_level_client = RestClient.builder(httpHosts:_*)
val high_level_client: RestHighLevelClient = new RestHighLevelClient(low_level_client)
答案 2 :(得分:0)
要使用多个主机创建高级REST客户端,您可以执行以下操作:
String[] esHosts = new String[]{"node1-example.com:9200", "node2-example.com:9200",
"node3-example.com:9200"};
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(esHosts)
.build();
RestHighLevelClient restClient = RestClients.create(clientConfiguration).rest();
// Hostnames used for building client can be verified as following
List<Node> nodes = restClient.getLowLevelClient().getNodes();
nodes.forEach(node -> System.out.println(node.toString()));
参考: