我正在編寫一個使用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
方法。我對scala
和apache httpClient
比較新。我必須頻繁地連接到幾個固定的服務器(即具有不同請求參數的5-6個固定URL)。
我經歷了多個在線資源,但仍然對此沒有信心。
- 是在多線程環境中使用http客戶端的最佳方式嗎?
- 是否有可能保持實時連接並將其用於各種請求?在這種情況下會有好處嗎?
- 我是否高效地使用/釋放所有資源?如果不是,請建議。
- 在Scala中使用它還是有一些更好的庫?
在此先感謝。
我建議你使用'https:// github.com/scalaj/scalaj-http'他們明確保證API是線程安全的。它看起來像Apache HTTPClient需要特定的多線程考慮。 http://hc.apache.org/httpclient-3.x/threading.html – maasg
我正在使用客戶端版本4.5.2。鏈接描述3.x –