我做的HTTP POST的频率非常高(> = 1 /秒)到API端点,我想确保我有效地这样做。我的目标是成功还是尽快失败,尤其是因为我有独立的代码,以重试失败的帖子。有 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连接的性能命中建立套接字连接的。您可以通过使用“保活”的HTTP连接避免这种情况。要做到这一点,最好使用HTTP 1.1,并确保“内容长度:XX”的请求和响应,始终设置“Connecction:关闭”设置正确适当的时候在接收时在正常作用

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top