我有n
个不同的来源,比如说,获得美元到欧元的汇率。让n = 3
和来源为Google,Yahoo,MyRates以及相应的方法:
def getYahooRate:Double = ???
def getGoogleRate:Double = ???
def getMyRate:Double = ???
我想查询美元兑换欧元的汇率,以便并行查询所有n
来源,并立即返回收到的第一个回复。如果在指定的时间范围内没有回复,则抛出异常。
使用Scala(以及必要的Akka)实现此方法的规范方法是什么?
是否有任何库方法可以完成大部分工作?
编辑:这是我尝试过的。关于代码的一些评论将不胜感激:这有点像来自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)
}
答案 0 :(得分:3)
您可以使用Future.firstCompletedOf
val first = Future.firstCompletedOf(futures)
Await.result(first, timeOut.millis)