Spring Data Elasticsearch请求触发SocketTimeoutException超时问题求助
问题描述
环境信息
- Java: 19
- Springboot: 3.0
依赖配置
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <version>5.0.2</version> </dependency>
配置类
import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.client.ClientConfiguration; import org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration; import org.springframework.data.elasticsearch.support.HttpHeaders; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @Configuration public class ElasticRestClientConfig extends ElasticsearchConfiguration { @Override public ClientConfiguration clientConfiguration() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Accept", "application/json"); httpHeaders.add("Content-Type", "application/json"); return ClientConfiguration.builder().connectedTo("search-*****.ap-south-1.es.amazonaws.com:9200") .usingSsl() .withPathPrefix("app") .withDefaultHeaders(httpHeaders) .withBasicAuth("", "") .withHeaders(() -> { HttpHeaders headers = new HttpHeaders(); headers.add("currentTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); return headers; }) .withBasicAuth("", "") .build(); } }
触发的异常
java.net.SocketTimeoutException: 5,000 milliseconds timeout on connection http-outgoing-0
解决方案
1. 调整客户端超时参数
默认5秒的套接字超时对于远程AWS ES服务来说过短,直接在ClientConfiguration中添加超时配置:
return ClientConfiguration.builder().connectedTo("search-*****.ap-south-1.es.amazonaws.com:9200") .usingSsl() .withPathPrefix("app") .withDefaultHeaders(httpHeaders) .withBasicAuth("", "") .withHeaders(() -> { HttpHeaders headers = new HttpHeaders(); headers.add("currentTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); return headers; }) // 新增超时配置 .withConnectTimeout(Duration.ofSeconds(10)) // 连接超时设为10秒 .withSocketTimeout(Duration.ofSeconds(30)) // 套接字读取超时设为30秒 .build();
同时删除重复的.withBasicAuth("", "")配置,避免冗余。
2. 排查网络连通性
- 用
curl测试应用服务器到ES端点的连通性:curl -v https://search-*****.ap-south-1.es.amazonaws.com:9200/app - 检查AWS安全组规则,确认应用服务器的IP地址被允许访问ES实例的9200端口。
3. 优化请求与ES集群状态
- 如果是大数据量查询,拆分请求为分页查询,减少单次请求的数据量;或者优化DSL语句,过滤不必要的数据。
- 查看AWS ES控制台的监控指标,确认集群是否存在CPU、内存过载情况,资源不足会导致响应缓慢引发超时。
4. 简化Header配置
当前同时使用withDefaultHeaders和withHeaders,检查是否有不必要的Header可以移除,避免额外的处理开销。
内容的提问来源于stack exchange,提问作者Prafulla Kumar Sahu
相关产品推荐
相关产品推荐

