0
Webサービスのjavaでhttp接続プーリングを実装しようとしています。このサービスは要求を受け取り、他のhttpサービスを呼び出します。JavaのHTTP接続プールでの接続の退避戦略
public final class HttpClientPool {
private static HttpClientPool instance = null;
private PoolingHttpClientConnectionManager manager;
private IdleConnectionMonitorThread monitorThread;
private final CloseableHttpClient client;
public static HttpClientPool getInstance() {
if (instance == null) {
synchronized(HttpClientPool.class) {
if (instance == null) {
instance = new HttpClientPool();
}
}
}
return instance;
}
private HttpClientPool() {
manager = new PoolingHttpClientConnectionManager();
client = HttpClients.custom().setConnectionManager(manager).build();
monitorThread = new IdleConnectionMonitorThread(manager);
monitorThread.setDaemon(true);
monitorThread.start();
}
public CloseableHttpClient getClient() {
return client;
}
}
class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized(this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(60, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
//
}
}
void shutdown() {
shutdown = true;
synchronized(this) {
notifyAll();
}
}
}
代わりに私が
manager.setValidateAfterInactivity
を使用する場合は、どのようなIdleConnectionMonitorThread
を使用しての接続立ち退き戦略にConnection Managementドキュメントで述べたように。上記の2つのアプローチの賛成論は何ですか?&?上記のHTTP接続プールの実装は正しいですか?
リンクで私の質問に投稿しましたhttps://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e418。 '古い接続チェックは100%信頼できるものではありません。アイドル接続のソケットモデルごとに1つのスレッドを含まない唯一の実行可能な解決策は、専用のモニタスレッドである。では、これは 'setValidateAfterInactivity'にも当てはまりますか? – tuk
はい、あります。古い接続チェックが比較的高価であると仮定すると、バージョン4.4以降のHttpClientは、すべての接続をチェックするのではなく、特定の期間非アクティブだったものだけをチェックします。 – oleg
'setValidateAfterInactivity'を正しく設定すると、 'setValidateAfterInactivity'で指定された数ms間アイドル状態になっていても、信頼できません。完全な信頼性が必要な場合は、 'IdleMonitorThread'アプローチを使用する必要があります。 – tuk