httpclient 연결을 효율적으로 재사용하려면 어떻게해야합니까?
-
19-09-2019 - |
문제
HTTP 게시물을 API 엔드 포인트에 매우 자주 (> = 1/sec)하고 있으며 효율적으로 수행하고 있는지 확인하고 싶습니다. 내 목표는 가능한 빨리 성공하거나 실패하는 것입니다. 특히 실패한 게시물을 재 시도 할 별도의 코드가 있기 때문에. 멋진 페이지가 있습니다 httpclient 성능 팁, 그러나 철저하게 구현하는 것이 실질적인 이점을 누릴 수 있는지 확실하지 않습니다. 지금 내 코드는 다음과 같습니다.
public class Poster {
private String url;
// re-use our request
private HttpClient client;
// re-use our method
private PostMethod method;
public Poster(String url) {
this.url = url;
// Set up the request for reuse.
HttpClientParams clientParams = new HttpClientParams();
clientParams.setSoTimeout(1000); // 1 second timeout.
this.client = new HttpClient(clientParams);
// don't check for stale connections, since we want to be as fast as possible?
// this.client.getParams().setParameter("http.connection.stalecheck", false);
this.method = new PostMethod(this.url);
// custom RetryHandler to prevent retry attempts
HttpMethodRetryHandler myretryhandler = new HttpMethodRetryHandler() {
public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
// For now, never retry
return false;
}
};
this.method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
}
protected boolean sendData(SensorData data) {
NameValuePair[] payload = {
// ...
};
method.setRequestBody(payload);
// Execute it and get the results.
try {
// Execute the POST method.
client.executeMethod(method);
} catch (IOException e) {
// unable to POST, deal with consequences here
method.releaseConnection();
return false;
}
// don't release so that it can be reused?
method.releaseConnection();
return method.getStatusCode() == HttpStatus.SC_OK;
}
}
오래된 연결 수표를 비활성화하는 것이 합리적입니까? 내가 사용하려면 MultithreadedConnectionManager? 물론 실제 벤치마킹이 도움이 될 수 있지만 내 코드가 먼저 올바른 트랙에 있는지 확인하고 싶었습니다.
해결책
HTTP 연결의 성능의 대부분은 소켓 연결을 설정하고 있습니다. 'Keep-Alive'HTTP 연결을 사용하여이를 피할 수 있습니다. 이렇게하려면 HTTP 1.1을 사용하고 "Content-Length : XX"가 항상 요청 및 응답으로 설정되어 있는지 확인하는 것이 가장 좋습니다. "Connecction : Close"는 적절한 경우 올바르게 설정되며 수신시 적절하게 작동합니다.
제휴하지 않습니다 StackOverflow