簡體   English   中英

如何有效地重用HttpClient連接?

[英]How can I reuse a HttpClient connection efficiently?

我非常頻繁地(> = 1 /秒)對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嗎? 當然,實際的基准測試會有所幫助,但我想先檢查一下我的代碼是否在正確的軌道上。

http連接的大部分性能都是建立套接字連接。 您可以通過使用“keep-alive”http連接來避免這種情況。 要做到這一點,最好使用HTTP 1.1並確保始終在請求和響應中設置“Content-Length:xx”,在適當時正確設置“Connecction:close”,並在收到時正確處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM