【问题标题】:Execute multiple tasks in parallel, pick answer from first completed并行执行多个任务,从第一个完成中选择答案
【发布时间】: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 questiontrycatch 的并行版本。以下方法的代码基于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


    【解决方案1】:

    您可以使用Future.firstCompletedOf

    val first = Future.firstCompletedOf(futures)
    Await.result(first, timeOut.millis)
    

    【讨论】:

    • 经过一段时间的尝试,这并没有达到预期的效果。如果第一个失败,它会返回而不是等待成功,这与我粘贴的代码不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多