どうすれば効率的にHttpClient接続を再利用することができますか?
-
19-09-2019 - |
質問
私は非常に頻繁(> = 1 /秒)APIエンドポイントへのHTTPポストをやっていると私は効率的にそれをやっていることを確認します。私の目標は、私が失敗した記事を再試行するために別のコードを持っている、特に以来、できるだけ早く成功するか失敗することです。そこの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接続のパフォーマンスヒットの多くは、ソケット接続を確立しています。あなたは、「キープアライブ」のHTTP接続を使用することによって、これを回避することができます。正しく正しく受信時に作用したとき、適切で設定されている
所属していません StackOverflow