java.io.IOException: listener timeout after waiting for [30000] ms
at org.elasticsearch.client.RestClient$SyncResponseListener.get(RestClient.java:660)
at org.elasticsearch.client.RestClient.performRequest(RestClient.java:219)
at org.elasticsearch.client.RestClient.performRequest(RestClient.java:191)
默认的监听超时,默认请求超过30秒就超时,因此在创建RestClient的时候需要设置超时时间:
查看RestClient.builder方法的源码,创建RestClientBuilder对象,并返回RestClient,看到有一个HttpClientConfigCallback属性,可以通过setRequestConfigCallback方法进行设置
public RestClientBuilder setRequestConfigCallback(RequestConfigCallback requestConfigCallback) {
Objects.requireNonNull(requestConfigCallback, "requestConfigCallback must not be null");
this.requestConfigCallback = requestConfigCallback;
return this;
}
下面直接看如何正确的去获取一个 Rest Client的代码
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.client.RestClient;
import static org.elasticsearch.client.RestClientBuilder.DEFAULT_CONNECTION_REQUEST_TIMEOUT_MILLIS;
/**
* ElasticSearch Rest Client Factory
*
* @author LiXuekai on 2019/7/8
*/
public class ElasticSearchRestClientFactory {
/**
* 超时时间设为5分钟
*/
private static final int TIME_OUT = 5 * 60 * 1000;
/**
* ElasticSearch Rest Client
*/
private static volatile RestClient restClient;
private ElasticSearchRestClientFactory() {
}
/**
* 单例模式获取连接ES客户端
*
* @param hostname es服务器地址,从配置文件获取
* @param port es服务的端口,从配置文件获取
* @return restClient
*/
public static RestClient getRestClient(final String hostname, final int port) {
if (restClient == null) {
synchronized (ElasticSearchRestClientFactory.class) {
if (restClient == null) {
restClient = RestClient.builder(new HttpHost(hostname, port))
.setMaxRetryTimeoutMillis(TIME_OUT)
.setHttpClientConfigCallback(httpClientBuilder -> {
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
//超时时间5分钟
.setConnectTimeout(TIME_OUT)
//这就是Socket超时时间设置
.setSocketTimeout(TIME_OUT)
.setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT_MILLIS);
httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
return httpClientBuilder;
})
.build();
}
}
}
return restClient;
}
}
使用注意:
1,使用单例模式去获取es连接,
2,设置超时以外,还的在复写个方法。