淘先锋技术网

首页 1 2 3 4 5 6 7

java springboot 使用ES客户端连接

一段时间闲置后,首次调用es命令会报SocketTimeOutException问题,再次调用不会报错

问题出现原因:

Elasticsearch 客户端会根据服务器返回的HTTP报文内容,来决定客户端保持HTTP连接Keep-Alive状态的策略。
如果结果如下,那么保持HTTP连接 Keep-Alive状态为120s

Connection: Keep-Alive
Keep-Alive: max=5, timeout = 120

如果不包含上述内容,那么客户端将保持Keep-Alive状态的时间为永久。
事实上,Elasticsearch服务器返回的报文,并没有上述HTTP头内容,所以客户端所有的HTTP连接都为永久保持Keep-Alive。
如果客户端长时间没有发送请求,服务器或者防火墙已经close了HTTP底层的TCP链接,但是此时客户端并不知道,由于Keep Alive是无限期,那么并不会重新建立连接,而是直接发送请求,此时就会得到SocketTimeout异常。

个人解决方案:
定期发类似ping的操作 保活

配置方式1:

@Configuration
public class EsConf {

    @Autowired
    LocalProperties localProperties;

    @Bean
    RestHighLevelClient elasticsearchClient() {
        ClientConfiguration configuration = ClientConfiguration.builder()
                .connectedTo(" 210.72.13.245:9200")
                .withHttpClientConfigurer(httpClientBuilder -> {
                    // httpclient保活策略
                    httpClientBuilder.setKeepAliveStrategy(((response, context) -> Duration.ofMinutes(2).toMillis()));
                    return httpClientBuilder;
                })
                //.withConnectTimeout(Duration.ofSeconds(5))
                .withSocketTimeout(Duration.ofSeconds(600))
                //.useSsl()
                //.withDefaultHeaders(defaultHeaders)
                //.withBasicAuth(username, password)
                // ... other options
                .build();
        RestHighLevelClient client = RestClients.create(configuration).rest();
        return client;
    }
}

配置方式2:

 @Bean(destroyMethod = "close")
    public RestHighLevelClient client() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(hostName, Integer.parseInt(port), scheme));
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setKeepAliveStrategy((response, context) -> Duration.ofMinutes(3).toMillis());
            httpClientBuilder.disableAuthCaching();
            return httpClientBuilder;
        });

        return new RestHighLevelClient(builder);
    }

参考文章:
https://www.dandelioncloud.cn/article/details/1578623608362856450