13

API エンドポイントに対して非常に頻繁に (>= 1/秒) 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の使用を検討する必要がありますか? もちろん、実際のベンチマークは役に立ちますが、最初に自分のコードが正しい軌道に乗っているかどうかを確認したかったのです。

4

1 に答える 1

5

http 接続のパフォーマンス ヒットの多くは、ソケット接続の確立です。これは、「キープアライブ」http 接続を使用することで回避できます。これを行うには、HTTP 1.1 を使用し、要求と応答で「Content-Length: xx」が常に設定されていること、「接続: close」が適切な場合に正しく設定され、受信時に適切に処理されることを確認することをお勧めします。

于 2011-05-18T21:14:27.227 に答える