0

我正在編寫一個使用apache httpclient(4.5.2)發佈一些文件內容並將狀態返回給調用者的單例類(Object in scala)。scala:多線程環境中的apache httpclient

object HttpUtils{ 
    protected val retryHandler = new HttpRequestRetryHandler() { 
    def retryRequest(exception: IOException, executionCount: Int, context: HttpContext): Boolean = { 
     //retry logic 
     true 
    } 
    } 
    private val connectionManager = new PoolingHttpClientConnectionManager() 

    // Reusing same client for each request that might be coming from different threads . 
    // Is it correct ???? 
    val httpClient = HttpClients.custom() 
    .setConnectionManager(connectionManager) 
    .setRetryHandler(retryHandler) 
    .build() 

    def restApiCall (url : String, rDD: RDD[SomeMessage]) : Boolean = { 
    // Creating new context for each request 
    val httpContext: HttpClientContext = HttpClientContext.create 
    val post = new HttpPost(url) 

    // convert RDD to text file using rDD.collect 

    // add this file as MultipartEntity to post 

    var response = None: Option[CloseableHttpResponse] // Is it correct way of using it ? 
    try { 
     response = Some(httpClient.execute(post, httpContext)) 
     val responseCode = response.get.getStatusLine.getStatusCode 
     EntityUtils.consume(response.get.getEntity) // Is it require ??? 
     if (responseCode == 200) true 
     else false 
    } 
    finally { 
     if (response.isDefined) response.get.close 
     post.releaseConnection() // Is it require ??? 
    } 
    } 
    def onShutDown = { 
    connectionManager.close() 
    httpClient.close() 
    } 
} 

多個線程(更具體地從火花流上下文)被調用restApiCall方法。我對scalaapache httpClient比較新。我必須頻繁地連接到幾個固定的服務器(即具有不同請求參數的5-6個固定URL)。

我經歷了多個在線資源,但仍然對此沒有信心。

  • 是在多線程環境中使用http客戶端的最佳方式嗎?
  • 是否有可能保持實時連接並將其用於各種請求?在這種情況下會有好處嗎?
  • 我是否高效地使用/釋放所有資源?如果不是,請建議。
  • 在Scala中使用它還是有一些更好的庫?

在此先感謝。

+0

我建議你使用'https:// github.com/scalaj/scalaj-http'他們明確保證API是線程安全的。它看起來像Apache HTTPClient需要特定的多線程考慮。 http://hc.apache.org/httpclient-3.x/threading.html – maasg

+0

我正在使用客戶端版本4.5.2。鏈接描述3.x –

回答

0

看來official docs有你所有的問題:

2.3.3。 Pooling連接管理器

PoolingHttpClientConnectionManager是一個更復雜的實現 ,它管理客戶端連接池並能夠服務來自多個執行線程的連接請求 。連接數爲 ,按每個路線彙總。 管理器已經在池中具有持續連接的請求將通過從池租用連接而不是創建 全新連接來爲 提供服務。

PoolingHttpClientConnectionManager每個路由和總共保持最大限制爲 連接。默認情況下,這個 實現將爲每個 給定路由創建不超過2個併發連接,總共不會有20個連接。對於許多現實世界的應用程序來說,這些限制可能會被證明過於嚴格,尤其是如果他們使用HTTP作爲其服務的傳輸協議。


2.4。多線程請求執行

當配備一個池的連接管理器,例如 PoolingClientConnectionManager,HttpClient的可以用來執行同時使用多個執行線程 多個請求。

PoolingClientConnectionManager將根據其配置分配連接 。如果給定路線的所有連接已經租用,則連接請求將被阻止,直到連接 被釋放回池。可以確保連接管理器 在連接請求操作中不會無限制地通過 將'http.conn-manager.timeout'設置爲正值。如果 連接請求在給定的時間段內不能被服務 ConnectionPoolTimeoutException將被拋出。

+0

我已閱讀本文檔,但沒有任何資源發佈的詳細示例/說明。我也經歷了Api的文檔,但沒有得到任何有用的東西。 –