HttpClient的连接管理器相关
Posted sh-0131
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient的连接管理器相关相关的知识,希望对你有一定的参考价值。
注意
public class ClientEvictExpiredConnections { public static void main(String[] args) throws Exception { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // 设置最大连接数 cm.setMaxTotal(200); // 设置每个主机地址的并发数 cm.setDefaultMaxPerRoute(20); new IdleConnectionEvictor(cm).start(); } public static class IdleConnectionEvictor extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionEvictor(HttpClientConnectionManager connMgr) { this.connMgr = connMgr; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // 关闭失效的连接 connMgr.closeExpiredConnections(); } } } catch (InterruptedException ex) { // 结束 } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } } }
定期关闭无效连接
public class ClientEvictExpiredConnections { public static void main(String[] args) throws Exception { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // 设置最大连接数 cm.setMaxTotal(200); // 设置每个主机地址的并发数 cm.setDefaultMaxPerRoute(20); new IdleConnectionEvictor(cm).start(); } public static class IdleConnectionEvictor extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionEvictor(HttpClientConnectionManager connMgr) { this.connMgr = connMgr; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // 关闭失效的连接 connMgr.closeExpiredConnections(); } } } catch (InterruptedException ex) { // 结束 } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } } }
设置请求参数
public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// 设置最大连接数
cm.setMaxTotal(200);
// 设置每个主机地址的并发数
cm.setDefaultMaxPerRoute(20);
new IdleConnectionEvictor(cm).start();
}
public static class IdleConnectionEvictor extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// 关闭失效的连接
connMgr.closeExpiredConnections();
}
}
} catch (InterruptedException ex) {
// 结束
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}
以上是关于HttpClient的连接管理器相关的主要内容,如果未能解决你的问题,请参考以下文章