我已经使用HttpClient3.1(Java)进行连接池,如下所示:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
public class HttpClientManager {
private static Logger logger = Logger.getLogger(HttpClientManager.class);
private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
private static HttpClientParams clientParams = new HttpClientParams();
static {
try {
clientParams.makeLenient();
clientParams.setAuthenticationPreemptive(false);
clientParams.setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(30000)); // set the so_timeout
clientParams.setParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, new Integer(3000)); // Head responses should come back in 3 seconds or less
clientParams.setParameter(HttpMethodParams.REJECT_HEAD_BODY, Boolean.TRUE); // We should reject any BODY sent as part of the HEAD request
clientParams.setParameter(HttpMethodParams.STATUS_LINE_GARBAGE_LIMIT, new Integer(0)); // We will not tolerate any garbage in the STATUS line
clientParams.setParameter(HttpClientParams.MAX_REDIRECTS, new Integer(5)); // We'll follow redirects 5 times.
clientParams.setConnectionManagerTimeout(30000); // We'll wait 30 seconds before timing out on getting a connection out of the connection manager
} catch(Throwable ex) {
logger.error("Exception setting timeouts etc for client connection factory", ex);
System.out.println("Exception setting timeouts etc for client connection factory"+ex);
}
}
private static HttpClient client = new HttpClient(clientParams, connectionManager);
/**
* Get a handle to a common HTTPClient that uses a multithreaded connection pool manager
* Code that uses this shares the pool.
* So it should be ok to use pools other than this one in case the threads in this pool are stuck on proxying web videos etc.
* @return
*/
public static HttpClient getClient() {
return client;
}
}
我通过以下方式获取客户端:HttpClient client = HttpClientManager.getClient();
并开始调用此方法,最后我调用method.releaseConnection();
但是
我大部分时间都得到以下异常:
java.net.SocketTimeoutException: Read timed out
java.net.SocketException: Software caused connection abort: recv failed
java.net.ConnectException: Connection timed out: connect
所以计划去httpclient4.3.2并看到一些代码,如下面的连接池:
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
cm.closeExpiredConnections();
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
没关系,或者还有其他方法可以实现吗?
感谢