如何有效地重用HttpClient连接?

时间:2010-02-10 19:34:24

标签: java http apache-commons-httpclient persistent-connection

我非常频繁地(> = 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吗?当然,实际的基准测试会有所帮助,但我想先检查一下我的代码是否在正确的轨道上。

1 个答案:

答案 0 :(得分:5)

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