下面列出了怎么用org.apache.http.nio.conn.NHttpClientConnectionManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void run() {
try {
while (!shutdown) {
sleep(15000);
List<NHttpClientConnectionManager> tmpConnMgrs;
synchronized (connMgrs) {
tmpConnMgrs = new ArrayList<NHttpClientConnectionManager>(connMgrs);
}
for (NHttpClientConnectionManager connMgr : tmpConnMgrs) {
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 60 sec
connMgr.closeIdleConnections(60, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
@Override
public void run() {
try {
while (!shutdown) {
sleep(15000);
List<NHttpClientConnectionManager> tmpConnMgrs;
synchronized (connMgrs) {
tmpConnMgrs = new ArrayList<NHttpClientConnectionManager>(connMgrs);
}
for (NHttpClientConnectionManager connMgr : tmpConnMgrs) {
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 60 sec
connMgr.closeIdleConnections(60, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
@Override
protected NHttpClientConnectionManager getAsyncConnectionManager() {
PoolingNHttpClientConnectionManager connectionManager = createUnconfiguredPoolingNHttpClientConnectionManager();
HttpClientConfig httpClientConfig = this.wrappedHttpClientConfig.getHttpClientConfig();
final Integer maxTotal = httpClientConfig.getMaxTotalConnection();
if (maxTotal != null) {
connectionManager.setMaxTotal(maxTotal);
}
final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute();
if (defaultMaxPerRoute != null) {
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
}
final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute();
for (Map.Entry<HttpRoute, Integer> entry : maxPerRoute.entrySet()) {
connectionManager.setMaxPerRoute(entry.getKey(), entry.getValue());
}
return connectionManager;
}
public HttpClient createInstance() {
final NHttpClientConnectionManager asyncConnectionManager = getAsyncConnectionManager();
CloseableHttpAsyncClient asyncHttpClient = createAsyncHttpClient(asyncConnectionManager);
HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory =
createHttpAsyncResponseConsumerFactory();
ServerPool serverPool = new ServerPool(new ArrayList<>(serverList));
return createConfiguredClient(
asyncHttpClient,
serverPool,
httpAsyncResponseConsumerFactory
);
}
@Test
public void createInstanceConfiguresAsyncHttpClient() {
// given
HttpClientFactory factory = Mockito.spy(createDefaultTestHttpClientFactory());
HttpClient client = spy(factory.createConfiguredClient(any(), any(), any()));
when(factory.createConfiguredClient(any(), any(), any())).thenReturn(client);
NHttpClientConnectionManager connectionManager = mock(NHttpClientConnectionManager.class);
when(factory.getAsyncConnectionManager()).thenReturn(connectionManager);
CloseableHttpAsyncClient httpAsyncClient = mock(CloseableHttpAsyncClient.class);
when(factory.createAsyncHttpClient(any())).thenReturn(httpAsyncClient);
// when
factory.createInstance();
// then
verify(factory, times(1)).createAsyncHttpClient(eq(connectionManager));
}
private NHttpClientConnectionManager getNHttpConnManager(Config config) throws IOException {
NHttpClientConnectionManager httpConnManager;
String connMgrStr = config.getString(HTTP_CONN_MANAGER);
switch (ApacheHttpClient.ConnManager.valueOf(connMgrStr.toUpperCase())) {
case POOLING:
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
PoolingNHttpClientConnectionManager poolingConnMgr = new PoolingNHttpClientConnectionManager(ioReactor);
poolingConnMgr.setMaxTotal(config.getInt(POOLING_CONN_MANAGER_MAX_TOTAL_CONN));
poolingConnMgr.setDefaultMaxPerRoute(config.getInt(POOLING_CONN_MANAGER_MAX_PER_CONN));
httpConnManager = poolingConnMgr;
break;
default:
throw new IllegalArgumentException(connMgrStr + " is not supported");
}
LOG.info("Using " + httpConnManager.getClass().getSimpleName());
return httpConnManager;
}
public void addConnMgr(NHttpClientConnectionManager connMgr) {
synchronized (connMgrs) {
if (CONNECTION_MANAGER_LIMIT > 0 && connMgrs.size() > CONNECTION_MANAGER_LIMIT) {
throw new ClientException("Too Many ServiceClient created.", null);
}
connMgrs.add(connMgr);
}
}
public void addConnMgr(NHttpClientConnectionManager connMgr) {
synchronized (connMgrs) {
if (CONNECTION_MANAGER_LIMIT > 0 && connMgrs.size() > CONNECTION_MANAGER_LIMIT) {
throw new ClientException("Too Many ServiceClient created.", null);
}
connMgrs.add(connMgr);
}
}
public static CloseableHttpAsyncClient create(RequestConfig config, NHttpClientConnectionManager connectionManager) {
HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();
builder.useSystemProperties().setRedirectStrategy(AlwaysRedirectStrategy.DEFAULT).addInterceptorLast(new RequestContent(true));
if (config != null)
builder.setDefaultRequestConfig(config);
if (connectionManager != null)
builder.setConnectionManager(connectionManager);
return builder.build();
}
@Override
public final JestClient getObject() {
// no other way than copying almost whole super.getObject() ..
BufferedJestHttpClient client = createDefaultClient();
HttpClientConfig httpClientConfig = wrappedHttpClientConfig.getHttpClientConfig();
client.setServers(httpClientConfig.getServerList());
final HttpClientConnectionManager connectionManager = getConnectionManager();
client.setHttpClient(createHttpClient(connectionManager));
final NHttpClientConnectionManager asyncConnectionManager = getAsyncConnectionManager();
client.setAsyncClient(createAsyncHttpClient(asyncConnectionManager));
// schedule idle connection reaping if configured
if (httpClientConfig.getMaxConnectionIdleTime() > 0) {
createConnectionReaper(client, connectionManager, asyncConnectionManager);
} else {
LOG.info("Idle connection reaping disabled");
}
// set discovery (should be set after setting the httpClient on jestClient)
if (httpClientConfig.isDiscoveryEnabled()) {
createNodeChecker(client, httpClientConfig);
} else {
LOG.info("Node Discovery disabled");
}
client.getAsyncClient().start();
return client;
}
IdleConnectionReaper createConnectionReaper(JestHttpClient client, HttpClientConnectionManager connectionManager, NHttpClientConnectionManager asyncConnectionManager) {
LOG.info("Idle connection reaping enabled...");
IdleConnectionReaper reaper = new IdleConnectionReaper(wrappedHttpClientConfig.getHttpClientConfig(),
new HttpReapableConnectionManager(connectionManager, asyncConnectionManager));
client.setIdleConnectionReaper(reaper);
reaper.startAsync();
reaper.awaitRunning();
return reaper;
}
protected CloseableHttpAsyncClient createAsyncHttpClient(NHttpClientConnectionManager connectionManager) {
return HttpAsyncClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(getRequestConfig())
.setProxyAuthenticationStrategy(wrappedHttpClientConfig.getHttpClientConfig().getProxyAuthenticationStrategy())
.setRoutePlanner(getRoutePlanner())
.setDefaultCredentialsProvider(wrappedHttpClientConfig.getHttpClientConfig().getCredentialsProvider())
.build();
}
protected CloseableHttpAsyncClient createAsyncHttpClient(NHttpClientConnectionManager connectionManager) {
return HttpAsyncClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(getDefaultRequestConfig())
.setDefaultCredentialsProvider(defaultCredentialsProvider)
.build();
}
public IdleConnectionEvictor(
NHttpClientConnectionManager connMgr,
long closePeriod)
{
this.connMgr = connMgr;
this.closePeriod = closePeriod;
}
public NIdleConnectionEvictor(
final NHttpClientConnectionManager connMgr,
final ThreadFactory threadFactory,
final long sleepTime, final TimeUnit sleepTimeUnit,
final long maxIdleTime, final TimeUnit maxIdleTimeUnit) {
//this.connMgr = Args.notNull(connMgr, "Connection manager");
this.connMgr = connMgr;
this.threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory();
this.sleepTimeMs = sleepTimeUnit != null ? sleepTimeUnit.toMillis(sleepTime) : sleepTime;
this.maxIdleTimeMs = maxIdleTimeUnit != null ? maxIdleTimeUnit.toMillis(maxIdleTime) : maxIdleTime;
this.thread = this.threadFactory.newThread(new Runnable() {
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(sleepTimeMs);
connMgr.closeExpiredConnections();
if (maxIdleTimeMs > 0) {
connMgr.closeIdleConnections(maxIdleTimeMs, TimeUnit.MILLISECONDS);
}
}
} catch (Exception ex) {
exception = ex;
}
}
});
}
public NIdleConnectionEvictor(
final NHttpClientConnectionManager connMgr,
final long maxIdleTime, final TimeUnit maxIdleTimeUnit) {
this(connMgr, null,
maxIdleTime > 0 ? maxIdleTime : 5, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS,
maxIdleTime, maxIdleTimeUnit);
}
/**
* Create connection manager for asynchronous http client.
*
* @return Connection manager for asynchronous http client.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
protected NHttpClientConnectionManager createNHttpClientConnectionManager() throws IOReactorException {
ConnectingIOReactor ioReactor =
new DefaultConnectingIOReactor(IOReactorConfig.custom()
.setSoTimeout(this.config.getSocketTimeoutInMillis()).setTcpNoDelay(true).build());
PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor);
connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections());
connectionManager.setMaxTotal(this.config.getMaxConnections());
return connectionManager;
}
/**
* Create asynchronous http client based on connection manager.
*
* @param connectionManager Asynchronous http client connection manager.
* @return Asynchronous http client based on connection manager.
*/
protected CloseableHttpAsyncClient createHttpAsyncClient(NHttpClientConnectionManager connectionManager) {
HttpAsyncClientBuilder builder = HttpAsyncClients.custom().setConnectionManager(connectionManager);
int socketBufferSizeInBytes = this.config.getSocketBufferSizeInBytes();
if (socketBufferSizeInBytes > 0) {
builder.setDefaultConnectionConfig(
ConnectionConfig.custom().setBufferSize(socketBufferSizeInBytes).build());
}
return builder.build();
}
public void removeConnMgr(NHttpClientConnectionManager connMgr) {
synchronized (connMgrs) {
connMgrs.remove(connMgr);
}
}
public void removeConnMgr(NHttpClientConnectionManager connMgr) {
synchronized (connMgrs) {
connMgrs.remove(connMgr);
}
}
protected NHttpClientConnectionManager getAsyncConnectionManager() {
PoolingNHttpClientConnectionManager connectionManager = createUnconfiguredPoolingNHttpClientConnectionManager();
connectionManager.setMaxTotal(maxTotalConnections);
return connectionManager;
}
public IdleConnectionEvictor(NHttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
public NIdleConnectionEvictor(
final NHttpClientConnectionManager connMgr,
final long sleepTime, final TimeUnit sleepTimeUnit,
final long maxIdleTime, final TimeUnit maxIdleTimeUnit) {
this(connMgr, null, sleepTime, sleepTimeUnit, maxIdleTime, maxIdleTimeUnit);
}
public NIdleConnectionEvictor setConnMgr(final NHttpClientConnectionManager connMgr){
this.connMgr = Args.notNull(connMgr, "Connection manager");
return this;
}