java elasticsearch连接超时设置异常返回
时间: 2023-11-18 14:11:54 浏览: 100
在 Java 中,可以通过设置 Elasticsearch 客户端的连接超时时间来解决连接超时的问题。以下是一个示例代码:
```
Settings settings = Settings.builder()
.put("cluster.name", "myClusterName")
.put("client.transport.sniff", true)
.build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
client.transport().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
client.transport().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
client.transport().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
client.admin().cluster().prepareHealth().setWaitForYellowStatus().get();
```
在上面的代码中,我们使用 Elasticsearch 的 TransportClient,设置了连接超时时间为 10 秒。如果在连接超时后仍然没有得到响应,就会抛出异常。
```
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300))
.setTimeout(TimeValue.timeValueSeconds(10));
```
如果还是有问题,可以尝试将 Elasticsearch 集群的连接数增加,或者在代码中进行重试。
阅读全文