JAVA程序连接es(Elasticsearch)会出现长时间不请求,突然请求会连接超时的问题
可以使用这个方法试试 设置长时间保持策略
伪代码
/** * 配置长连接保持策略 * * @return */ public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() { return (response, context) -> { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); log.info("HeaderElement:{}", JSON.toJSONString(he)); String param = he.getName(); String value = he.getValue(); if (value != null && "timeout".equalsIgnoreCase(param)) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { log.error("解析长连接过期时间异常", ignore); } } } HttpHost target = (HttpHost) context.getAttribute( HttpClientContext.HTTP_TARGET_HOST); //如果请求目标地址,单独配置了长连接保持时间,使用该配置 Optional<Map.Entry<String, Integer>> any = Optional.ofNullable(httpClientPoolConfig.getKeepAliveTargetHost()).orElseGet(HashMap::new) .entrySet().stream().filter( e -> e.getKey().equalsIgnoreCase(target.getHostName())).findAny(); //否则使用默认长连接保持时间 return any.map(en -> en.getValue() * 1000L).orElse(httpClientPoolConfig.getKeepAliveTime() * 1000L); }; }
调用 根据自己实际的连接方式来 这里只是设置了其中一个参数
RestClientBuilder builder = RestClient.builder(httpHosts).setRequestConfigCallback(requestConfigBuilder -> { requestConfigBuilder.setConnectTimeout(5000); requestConfigBuilder.setSocketTimeout(40000); requestConfigBuilder.setConnectionRequestTimeout(1000); return requestConfigBuilder; }); if (null != username && null != password) { final CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); builder.setHttpClientConfigCallback(httpClientBuilder -> { httpClientBuilder.disableAuthCaching(); httpClientBuilder.setDefaultCredentialsProvider(provider); httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy()); return httpClientBuilder; }); }
如果出现报错
Caused by: org.apache.http.ContentTooLongException: entity content is too long [331503558] for the configured buffer limit [104857600]
at org.elasticsearch.client.HeapBufferedAsyncResponseConsumer.onEntityEnclosed(HeapBufferedAsyncResponseConsumer.java:76)
at org.apache.http.nio.protocol.AbstractAsyncResponseConsumer.responseReceived(AbstractAsyncResponseConsumer.java:137)
at org.apache.http.impl.nio.client.MainClientExec.responseReceived(MainClientExec.java:315)
at org.apache.http.impl.nio.client.DefaultClientExchangeHandlerImpl.responseReceived(DefaultClientExchangeHandlerImpl.java:151)
at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.responseReceived(HttpAsyncRequestExecutor.java:309)