【发布时间】:2011-01-15 10:24:47
【问题描述】:
我非常频繁地 (>= 1/秒) 对 API 端点执行 HTTP POST,并且我想确保我正在高效地执行此操作。我的目标是尽快成功或失败,特别是因为我有单独的代码来重试失败的 POST。 HttpClient performance tips 有一个不错的页面,但我不确定详尽实施它们是否会带来真正的好处。这是我现在的代码:
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 多次浏览)。如果您有一些建议,回答这个问题可能是赢得一些声誉的好方法。 ;-)
标签: java http apache-commons-httpclient persistent-connection