如何高效地重用 HttpClient 连接?

14
我经常(>= 1/sec)向API端点进行HTTP POST,并希望确保我的操作高效。我的目标是尽快成功或失败,特别是因为我有单独的代码来重试失败的POST。这里有一个很好的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吗?当然,实际基准测试会有所帮助,但我想先检查一下我的代码是否正确。


7
尽管没有回答,我还是获得了受欢迎问题徽章(1000+ 次浏览),这有点讽刺。如果你有一些建议,回答这个问题可能是赚取声望的好方法。;-) - pr1001
https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html - Christophe Roussy
1个回答

5

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接