要解决并行线程工作中的HTTP请求偶尔被延迟和终止的问题,可以尝试以下解决方法:
import org.apache.http.client.config.RequestConfig;
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 设置连接超时时间
.setSocketTimeout(5000) // 设置读取超时时间
.build();
HttpGet httpGet = new HttpGet("http://example.com");
httpGet.setConfig(requestConfig);
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(100); // 设置最大连接数
connectionManager.setDefaultMaxPerRoute(20); // 设置每个路由的最大连接数
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.build();
HttpGet httpGet = new HttpGet("http://example.com");
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.protocol.HttpContext;
HttpRequestRetryHandler retryHandler = (exception, executionCount, context) -> {
if (executionCount >= 3) { // 最多重试3次
return false;
}
if (exception instanceof NoHttpResponseException) { // 服务器未响应时重试
return true;
}
return false;
};
CloseableHttpClient httpClient = HttpClients.custom()
.setRetryHandler(retryHandler)
.build();
HttpGet httpGet = new HttpGet("http://example.com");
通过以上方法,我们可以优化并行线程工作中的HTTP请求,提高请求的稳定性和效率。不过请注意,以上代码示例仅为参考,具体的实现可能需要根据具体的应用场景进行调整和优化。