来自Akka的异步io的迟到回复

时间:2012-08-23 15:39:22

标签: scala akka

我正在使用akka一段时间。我开始在我的代码中看到一些模式来解决异步io的延迟回复。这个实现好吗?还有另一种方法可以在没有阻止的情况下进行延迟回复吗?

class ApplicationApi(asyncIo : ActorRef) extends Actor {
    // store senders to late reply
    val waiting = Map[request, ActorRef]()

    def receive = {
        // an actore request for a user, store it to late reply and ask for asyncIo actor to do the real job
        case request : GetUser => 
            waiting += (sender -> request)
            asyncIo ! AsyncGet("http://app/user/" + request.userId)
        // asyncio response, parse and reply
        case response : AsyncResponse =>
            val user = parseUser(response.body)
            waiting.remove(response.request) match {
                case Some(actor) => actor ! GetUserResponse(user)
            }
    }
}

1 个答案:

答案 0 :(得分:5)

在等待回复时避免阻止的一种方法是使用ask方法-a.k.a发送。 ?运算符 - 返回Future(与!不同,返回())。

使用onSuccessforeach方法,您可以指定在将来/何时通过回复完成时要执行的操作。要使用此功能,您需要混合使用AskSupport特征:

class ApplicationApi(asyncIo : ActorRef) extends Actor with AskSupport {

  def receive = {
    case request: GetUser =>
      val replyTo = sender
      asyncIo ? AsyncGet("http://app/user/" + request.userId) onSuccess {
        case response: AsyncResponse =>
          val user = parseUser(response.body)
          replyTo ! GetUserResponse(user)
      }

}

避免使用此技术执行修改ApplicationApi actor状态的任何副作用,因为效果将与接收循环不同步。但是,将消息转发给其他参与者应该是安全的。


顺便说一句,这是捕捉当前sender作为模式匹配的一部分的技巧,避免以后需要将其分配给变量。

trait FromSupport { this: Actor =>
  case object from {
    def unapply(msg: Any) = Some(msg, sender)
  }
}

class MyActor extends Actor with FromSupport {
  def receive = {
    case (request: GetUser) from sender =>
      // sender is now a variable (shadowing the method) that is safe to use in a closure
  }
}