12
我正在非常頻繁地(> = 1 /秒)對API端點進行HTTP POST,我想確保我正在有效地進行操作。我的目標是儘快成功或失敗,特別是因爲我有單獨的代碼來重試失敗的POST。有一個不錯的頁面HttpClient performance tips,但我不確定是否全面實施它們都會帶來真正的好處。這裏是我的代碼現在:如何有效地重用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?當然,實際的基準測試會有所幫助,但我想檢查我的代碼是否在正確的軌道上。
儘管沒有答案,但我贏得了熱門問題徽章(1000多個視圖),這很具有諷刺意味。如果你有一些建議,回答這個問題可能是贏得聲譽的好方法。 ;-) – pr1001
https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html –