我正在使用ApacheHTTP客户端来实现HTTP连接池,并且我有一个要求,每次连接池创建连接时都要调用一个方法。我检查了它是否允许我们覆盖创建连接的方法,但它没有。有办法实现这一点吗?
import org.apache.http.*;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.TargetAuthenticationStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.util.concurrent.TimeUnit;
public class PoolingConnectionFactory {
public PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
public CloseableHttpClient CreateHttpClient(PoolingHttpClientConnectionManager connManager) {
CloseableHttpClient client = HttpClients.custom()
.setTargetAuthenticationStrategy(new AuthendictionSessionStrategy())
.setKeepAliveStrategy(strategy)
.setConnectionManager(connManager)
.build();
return client;
}
public CloseableHttpClient getConnection(PoolingHttpClientConnectionManager connMan) {
connMan.closeExpiredConnections(); //Close the expired http connections which are expired
connMan.closeIdleConnections(50, TimeUnit.SECONDS); //if http connection is idle for 50s then it will close
CloseableHttpClient client = CreateHttpClient(connMan);
return client;
}
}
有多个插件点。可以在套接字工厂级别或连接运算符级别注入自定义代码。
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
new DefaultHttpClientConnectionOperator(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory() {
@Override
public Socket connectSocket(
int connectTimeout,
Socket socket,
HttpHost host,
InetSocketAddress remoteAddress,
InetSocketAddress localAddress,
HttpContext context) throws IOException {
return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
}
})
.register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()) {
@Override
public Socket connectSocket(
int connectTimeout,
Socket socket,
HttpHost host,
InetSocketAddress remoteAddress,
InetSocketAddress localAddress,
HttpContext context) throws IOException {
return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
}
})
.build(),
DefaultSchemePortResolver.INSTANCE,
SystemDefaultDnsResolver.INSTANCE) {
@Override
public void connect(
ManagedHttpClientConnection conn,
HttpHost host,
InetSocketAddress localAddress,
int connectTimeout,
SocketConfig socketConfig,
HttpContext context) throws IOException {
super.connect(conn, host, localAddress, connectTimeout, socketConfig, context);
}
},
ManagedHttpClientConnectionFactory.INSTANCE,
0L, TimeUnit.MILLISECONDS);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(cm)
.build();