【发布时间】:2016-04-18 17:47:58
【问题描述】:
我有 n 不同的来源,例如,获取美元兑欧元的汇率。假设n = 3 和来源是 Google、Yahoo、MyRates 和相应的方法:
def getYahooRate:Double = ???
def getGoogleRate:Double = ???
def getMyRate:Double = ???
我想查询美元兑欧元的汇率,这样所有n 来源都被并行轮询,并立即返回收到的第一个响应。如果在指定的时间范围内没有回复,则抛出异常。
使用 Scala(以及如果需要 Akka)实现这一点的规范方法是什么?
是否有任何库方法可以完成大部分工作?
编辑:这是我尝试过的。代码上的一些 cmets 将不胜感激:
这有点像this SO question 中trycatch 的并行版本。以下方法的代码基于this SO answer
type unitToT[T] = ()=>T
def trycatchPar[B](list:List[unitToT[B]], timeOut:Long):B = {
if (list.isEmpty) throw new Exception("call list must be non-empty")
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.util.Failure
import scala.util.Success
val p = promise[B]
val futures = list.map(l => Future{l()})
futures foreach {
_ onComplete {
case s @ Success(_) => {
// Arbitrarily return the first success
p tryComplete s
}
case s @ Failure(_) =>
}
}
Await.result(p.future, timeOut millis)
}
【问题讨论】:
标签: scala akka scala-2.11