如何在播放中的演员之间传递回复!和阿卡

时间:2012-08-22 04:21:47

标签: scala playframework-2.0 akka

我正在使用Play 2.0和Akka来部署Web应用程序。我根据责任分离了演员,因为演员经常需要在单个网络请求中相互沟通。

例如,给定一个管理注册设备的actor,它必须查询处理相关用户帐户的另一个actor:

class DeviceActor extends Actor {

  val accountActorRef = ...

  def receive = {
    case GetAccountByDeviceId(id:String) =>
      val accountId = getAccountIdAssociatedWithDevice(id)
      accountActorRef ? GetAccountById(accountId) map {
        case account: Account => sender ! account
      }
  }

}

从我的控制器调用DeviceActor时,我总是得到

akka.pattern.AskTimeoutException

1 个答案:

答案 0 :(得分:6)

mapFuture上调用Promise时,您实际上正在注册回调。引用sender在回调闭包中被捕获,但sender仅在DeviceActor处理消息时正确设置。

您必须在存在receive方法之前捕获发件人引用

class DeviceActor extends Actor {

  val accountActorRef = ...

  def receive = {
    case GetAccountByDeviceId(id:String) =>
      val X = sender
      val accountId = getAccountIdAssociatedWithDevice(id)
      accountActorRef ? GetAccountById(accountId) map {
        case account: Account => X ! account
      }
  }

}