5

私はしばらく akka を使用しています。async 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)
            }
    }
}
4

1 に答える 1

5

返信を待っている間のブロックを回避する 1 つの方法は、askメソッド (オペレーター?)を使用して送信することです。Future!()

onSuccessまたはメソッドを使用しforeachて、Future が返信で完了した場合に実行するアクションを指定できます。これを使用するには、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は、効果が受信ループと非同期で発生するためです。ただし、他のアクターへのメッセージの転送は安全なはずです。


ところで、senderパターン マッチの一部として current をキャプチャし、後で変数に代入する必要がないようにするためのトリックを次に示します。

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
  }
}
于 2012-08-23T16:20:00.930 に答える