Akka演员/ scala - 单个onSuccess多个问题

时间:2014-10-13 15:13:58

标签: scala akka actor

我有一连串的akka​​演员,比如

A --> B --> C

演员A'问'演员B反过来'问'演员C. 演员A需要等到演员C完成处理。 B是一个薄层,除了将消息传递(询问)到C并将Future返回给A之外什么都没做。基本上B只做

        { case msgFromA => sender ! C ? msgFromA }

因此,A所获得的是未来[任何]。

A处理请求的方式是使用嵌套映射

actorRefFactory.actorOf(Props[A]) ? msgA map {
        resp =>
          // Type cast Any to Future and use another map to complete processing. 
          resp.asInstanceOf[Future[_]] map {
            case Success =>
              // Complete processing
            case Failure(exc) =>
             // Log error

这是有效的(即最终处理仅在演员C完成处理时发生)但不用说它看起来很糟糕。我尝试使用平板图但无法使其正常工作。任何让它看起来很好的想法:) 感谢

1 个答案:

答案 0 :(得分:4)

更合适的方式:

A

val f: Future[MyType] = (B ? msg).mapTo[MyType]
f onComplete {
  case Success(res) => // do something
  case Failure(t) => // do something
}

B中,使用forward

{ case msgFromA => C forward msgFromA }

C

// call database
// update cache
sender() ! res   // actually sends to A