【问题标题】:Akka actor cannot send back the messageAkka 演员无法发回消息
【发布时间】:2015-03-28 11:23:28
【问题描述】:

比如说,我有一个 Actor,它的接收函数喜欢

def receive = {
  case Message =>
    val doFuture: Future[String] = doSomething()

    doFuture onSuccess {
      case doResult =>
        //////////// Here is the problem !! /////////////
        // --> here fail. Seems sender cannot send back the result to the caller
        sender ! doResult
    }

    doFuture onFailure {
      // handle exception
    }
}

为什么发件人不能再发回消息了?

【问题讨论】:

标签: scala akka actor


【解决方案1】:
def receive = {
  case Message =>
    val doFuture: Future[String] = doSomething()
    val requester = sender

    doFuture onSuccess {
      case doResult =>
        requester ! doResult
    }

    doFuture onFailure {
      // handle exception
    }
}

您可以保存您的原始发件人然后使用它(以防您出于某种原因不想使用管道)。不管怎样,管道看起来好多了,而且是专门为这种情况设计的:

import akka.pattern.pipe

 def receive = {
      case Message =>
          val doFuture: Future[String] = doSomething()  
          doFuture pipeTo sender
 }

【讨论】:

    【解决方案2】:

    这就是pipeTo 的用途:

    import akka.pattern.pipe
    
    ...
    
    doFuture.pipeTo(sender())
    

    【讨论】:

      猜你喜欢
      • 2012-10-09
      • 1970-01-01
      • 2018-09-29
      • 2014-12-02
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      相关资源
      最近更新 更多