我将使用Dispatch编写一个简单的HTTP客户端。我打电话给dispatch.Http
以获得未来并致电未来以获得回复
val request = ... val future = Http(request) // call the server asynchronously val response = future() // wait for the response from the server
现在我想知道如何等待超时。我希望最后一次API调用是:
// throw an exception if no response received within timeout val response = future(timeout: Long)
有意义吗?
我理解Dispatch
返回scala.concurrent.Future
,它不提供API超时。你会如何建议我实施它?
答案 0 :(得分:5)
您可以创建已配置的Http客户端:
val httpApplicationClient = Http.configure( _.setRequestTimeoutInMs(3000) )
val future = httpApplicationClient(request)
...
答案 1 :(得分:3)
首先,您可以使用Await:
import scala.concurrent.Await
import scala.concurrent.duration._
Await.result(future, 10 seconds) //you can specify timeout here
问题是如果未来无法在指定的超时时间内返回,它将抛出异常。
如果您需要更多灵活性,那么第二种方法是:
val futureTimeout = Promise.timeout("Timed out" /* or throw new RuntimeException("timed out") */, 10 seconds)
Future.firstCompletedOf(Seq(futureResult, futureTimeout)).map {
case result: SomeType => //do something
case timedOut: SomeOtherType => //handle timeout
}