akka - 如何获得几个演员的结果?

时间:2017-06-27 08:50:14

标签: java akka

我想知道是否有最佳做法向2个不同的演员发送2条消息

并等待所有这些(当然得到结果)以继续执行。

即类似:

send message to actor 1
send message to actor 2
List<results> = wait.all(actor1,actor2)

1 个答案:

答案 0 :(得分:1)

您可能正在寻找ask pattern结合Future.sequencefor - 理解力:

import akka.pattern.ask

case object Request

implicit val timeout = Timeout(5 seconds) // needed for `?` below

// Ask your actors for a result
val f1 = actorA ? Request
val f2 = actorB ? Request
val f3 = actorC ? Request

// for-comprehension
(for {
    x <- f1
    s <- f2
    d <- f3
} yield (f1, f2, f3)).map {
    case (r1, r2, r3) =>
        //Do your stuff with the results
}

// Future.sequence
Future.sequence(f1, f2, f3).map {
    case (r1, r2, r3) =>
        //Do your stuff with the results
}