您的位置:首页 > Web前端 > Node.js

Java连接elasticsearch集群 NoNodeAvailableException 解决方法

2017-04-20 17:26 441 查看
以下是java连接elasticsearch集群,新增一个index的客户端代码

package com.yyfq.report.test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

public class ElasticsearchTest {
public static void main(String[] argv) throws UnknownHostException{
//客户端连接elasticsearch代码
Map<String, String> map = new HashMap();
map.put("cluster.name", "elasticsearch");
Settings.Builder settings = Settings.builder().put(map).put("client.transport.ignore_cluster_name", true);
Client client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(
InetAddress.getByName("127.0.0.1"), Integer.parseInt("9200")));
// 新增一个index
IndexResponse response = client.prepareIndex("twitter", "tweet")
.setId("1")
.setSource("{'counter':'2','tags':'Add one more!''}")
.execute()
.actionGet();
System.out.println("response.version():"+response.getVersion());

//关闭客户端
client.close();
}
}
执行以上代码时会抛出一个错误:Exception in thread "main" NoNodeAvailableException[None of the configured nodes are available......

解决方法: 

1. 端口号不能与HTTP设置的端口号一致!!!! 



2. 集权名称如果与elasticsearch.yml 中定义的一致,或者默认的elasticsearh, setting必须为Setting.Empty

   下面是改正过的连接方案。

public class ElasticsearchTest {
public static void main(String[] argv) throws NumberFormatException, UnknownHostException{

/* //设置新集群名称
Settings settings = Settings.builder()
.put("cluster.name", "newCluster")
.put("node.name","newNode").build();*/

//创建client
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

//搜索数据
GetResponse response = client.prepareGet("twitter", "tweet", "1").execute().actionGet();

//输出结果
System.out.println(response.getSourceAsString());

//关闭client

client.close();
}
}


 3. 如果不是端口号和集群名称的问题,请检查你的jar包版本是否对应elasticsearch版本

     我用的elasticsearch 5.1.1, 对应的Maven jar包依赖    



  希望这篇文章能帮到你!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  elasticsearch
相关文章推荐