通过TransportClient在java中使用Elasticsearch

时间:2017-09-12 10:21:24

标签: java elasticsearch

我试图通过TransportClient在java中使用elasticsearch。我使用logstash将mysql与elasticsearch集成。 这就是我初始化和使用传输客户端的方式

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9200));

我无法连接到节点,我得到握手超时。 我收到以下错误:

TransportClientNodesService - failed to connect to node 
[{#transport#-1}{vrvVU4MGTAC7_5NCOiBseg}{localhost}{127.0.0.1:9200}], 
ignoring...
org.elasticsearch.transport.ConnectTransportException: [][127.0.0.1:9200] handshake_timeout[30s]
at org.elasticsearch.transport.TcpTransport.executeHandshake(TcpTransport.java:1614) ~[elasticsearch-5.5.2.jar:5.5.2]
at org.elasticsearch.transport.TcpTransport.openConnection(TcpTransport.java:555) ~[elasticsearch-5.5.2.jar:5.5.2]
at org.elasticsearch.transport.TcpTransport.openConnection(TcpTransport.java:116) ~[elasticsearch-5.5.2.jar:5.5.2]
at org.elasticsearch.transport.TransportService.openConnection(TransportService.java:351) ~[elasticsearch-5.5.2.jar:5.5.2]
at org.elasticsearch.client.transport.TransportClientNodesService$SimpleNodeSampler.doSample(TransportClientNodesService.java:407) [elasticsearch-5.5.2.jar:5.5.2]
at org.elasticsearch.client.transport.TransportClientNodesService$NodeSampler.sample(TransportClientNodesService.java:357) [elasticsearch-5.5.2.jar:5.5.2]
at org.elasticsearch.client.transport.TransportClientNodesService$ScheduledNodeSampler.run(TransportClientNodesService.java:390) [elasticsearch-5.5.2.jar:5.5.2]
at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:569) [elasticsearch-5.5.2.jar:5.5.2]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_131]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_131]

1 个答案:

答案 0 :(得分:4)

Elasticsearch传输端口为9300,因此请使用9300替换9200来更改您的客户端创建行,如下所示:

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));

查找相关文档here

如果您使用的是默认(cluster.name)以外的其他elasticsearch,则必须在创建TransportClient时进行设置,如下所示:

Settings settings = Settings.builder()
        .put("cluster.name", "myClusterName").build();
TransportClient client = new PreBuiltTransportClient(settings);
//Add transport addresses and do something with the client...