问题描述:
在springboot项目中使用TransportClient方式连接ES,完整报错:
org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available
背景
SpringBoot版本:1.5.11 ES版本:7.0.0 项目中配置文件:
spring.data.elasticsearch.cluster-name=elasticsearch spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
本地ES配置:使用默认配置,(默认配置cluster-name为elasticsearch) 测试连接的代码:
import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.transport.client.PreBuiltTransportClient;
public static void main(String[] argv) throws NumberFormatException, UnknownHostException {
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); //ES服务器的地址,端口使用9300哦 Map json = new HashMap(); //需要插入的json数据 json.put("user", "kimchy"); json.put("postDate", new Date()); json.put("message", "trying out Elasticsearch"); IndexResponse indexResponse = client.prepareIndex("customer", "doc", "3").setSource(json, XContentType.JSON).get(); //customer是索引名字,需要先创建哦,_doc是类型,相当于索引下面的一个分区,3是这条数据的唯一ID,如果索引,类型,ID都相同,执///行该操作则会执行修改操作 String index = indexResponse.getIndex(); String type = indexResponse.getType(); String id = indexResponse.getId(); long version = indexResponse.getVersion(); System.out.println(index); System.out.println(type); System.out.println(id); System.out.println(version); RestStatus status = indexResponse.status(); client.close(); }
原因:
分析:由于报错显示没有可用的ES node节点,因此可能是配置连接的cluster-name和ES配置的值不一样(如果报这个错了,优先考虑这个因素,具体解决方法很简单,确认ES安装目录下config下elasticsearch.yml文件中配置的cluster.name和代码中配置的名字是否相同),但是在这里排除了这个原因,因为我默认都是elasticsearch。后面无意中看到ES7版本后不支持TransportClient方式连接了(还是得多关注官方文档啊),所以解决办法很简单,下载ES6版本,重新启动下就OK了。 结论: 确认cluster.name是否相同 确认版本是否一致 本人亲测:
org.elasticsearch.client transport 5.4.0
org.apache.logging.log4j log4j-core 2.11.1
在resources目录下创建log4j2.properties日志文件,内容:
appender.console.type = Console appender.console.name = console appender.console.layout.type = PatternLayout
rootLogger.level = info rootLogger.appenderRef.console.ref = console
_doc开头的文档不允许存在否则会报错