2010-02-10 69 views
12

我正在非常頻繁地(> = 1 /秒)對API端點進行HTTP POST,我想確保我正在有效地進行操作。我的目標是儘快成功或失敗,特別是因爲我有單獨的代碼來重試失敗的POST。有一個不錯的頁面HttpClient performance tips,但我不確定是否全面實施它們都會帶來真正的好處。這裏是我的代碼現在:如何有效地重用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

儘管沒有答案,但我贏得了熱門問題徽章(1000多個視圖),這很具有諷刺意味。如果你有一些建議,回答這個問題可能是贏得聲譽的好方法。 ;-) – pr1001

+0

https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html –

回答

5

http連接的大部分性能命中是建立套接字連接。你可以通過使用'keep-alive'http連接來避免這種情況。爲此,最好使用HTTP 1.1並確保在請求和響應中始終設置「Content-Length:xx」,並在適當時正確設置「Connecction:close」,並在收到時正確採取行動。