gpt4 book ai didi

java - 如何有效地重用 HttpClient 连接?

转载 作者:搜寻专家 更新时间:2023-10-30 21:11:53 26 4
gpt4 key购买 nike

我对 API 端点执行 HTTP POST 非常频繁(>= 1/秒),我想确保我的执行效率很高。我的目标是尽快成功或失败,特别是因为我有单独的代码来重试失败的 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 吗? ?当然,实际的基准测试会有帮助,但我想先检查我的代码是否在正确的轨道上。

最佳答案

http 连接的大部分性能损失是建立套接字连接。您可以通过使用“keep-alive”http 连接来避免这种情况。为此,最好使用 HTTP 1.1 并确保始终在请求和响应中设置“Content-Length: xx”,在适当的时候正确设置“Connection: close”并在收到时正确执行。

关于java - 如何有效地重用 HttpClient 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2239741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com