2017-02-24 8 views
0

웹 서비스 용으로 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 문서에서 언급 한 바와 같이
  1. . 위의 두 접근 방식의 장점은 무엇입니까 &?

  2. 위의 HTTP 연결 풀 구현이 맞습니까?

답변

1

#setValidateAfterInactivity은 긍정적 인 값으로 설정되어 있고 영구 연결은 임대 요청시 유효성이 검사됩니다. 즉, 부실하고 재사용 할 수없는 연결은 다시 사용하려고 시도 할 때까지 풀에서 자동으로 제거되지 않습니다.

지정된 시간 간격에 영구 연결을 반복하고 풀에서 만료 된 연결 또는 유휴 연결을 제거하는 전용 스레드를 실행하면 사전 스레드 제거 및 여분의 풀 잠금 경합으로 사전 예방적인 연결 제거가 보장됩니다.

+0

내 질문에 게시 된 링크 https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e418. '부실 연결 점검은 100 % 신뢰할만한 것이 아닙니다. 유휴 연결에 대한 소켓 모델 당 하나의 스레드를 포함하지 않는 유일한 실현 가능한 솔루션은 전용 모니터 스레드입니다. 그럼'setValidateAfterInactivity'에 대해서도 마찬가지입니까? – tuk

+0

네, 그렇습니다. 부실 연결 검사가 상대적으로 비싸다는 것을 감안할 때 4.4 버전의 HttpClient는 더 이상 모든 연결을 검사하지 않고 특정 시간 동안 비활성 상태 인 것만 확인합니다. – oleg

+0

'setValidateAfterInactivity'를 올바르게 설정하면 연결이 끊어지면 부실 체크가 실행됩니다 'setValidateAfterInactivity'에 지정된만큼 많은 ms 동안 유휴 상태입니다. 완전한 신뢰성을 원하면'IdleMonitorThread' 접근 방식을 사용해야합니까? – tuk