سؤال

أقوم بعمل HTTP وظائف في كثير من الأحيان (> = 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;
  }
}

هل من المنطقي تعطيل التحقق من الاتصالات التي لا معنى لها؟ يجب أن أبحث في استخدام multithreadedconectionmanager.ب بطبيعة الحال، فإن القياس الفعلي من شأنه أن يساعد ولكن أردت التحقق مما إذا كان الرمز الخاص بي على المسار الصحيح أولا.

هل كانت مفيدة؟

المحلول

الكثير من أداء أداء اتصالات HTTP هو إنشاء اتصال مأخذ التوصيل. يمكنك تجنب ذلك باستخدام اتصالات HTTP "البقاء على قيد الحياة". للقيام بذلك، من الأفضل استخدام HTTP 1.1 وتأكد من تعيين "طول المحتوى: XX" دائما في الطلبات والردود، "Connecrction: إغلاق" يتم تعيينه بشكل صحيح عند الاقتضاء ويتم تصرفه بشكل صحيح عند استلامه.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top