Akka-Http:如何从演员那里回复?

时间:2016-06-01 22:45:26

标签: scala akka akka-http

我在请求中使用了一个带有“ask”模式的actor:

val route =
    pathPrefix("myapp") {
      path("search") {
        get {
          (mainActorRef ? DoSomething("foo")).mapTo[ReturningType].map { result =>
  complete(HttpEntity(ContentTypes.`application/json`, result ))
         }
        }
      }
    }

问题是主要演员与其他演员沟通并从其中一个演员那里得到答案:

class MainActor extends Actor {

  override def receive: Receive = {

    case d:DoSomething =>
      anotherActor ! DoThis(d)

    // received from anotherActor as reply to DoThis
    case r:DoThisResponse =>
      // how do I send the response back to my “route”?
      pipe (Future{r}) to ???
  }

}

如何将此答案作为回复发送回Akka-Http?

在主actor中使用“sender()”不起作用,因为它不是正确的引用。我是否应该在主要演员内传递DoSomething一些与“tell”(!)一起使用的引用?如何通过此参考?

1 个答案:

答案 0 :(得分:2)

发送至tell时,MainActor使用forward代替anotherActor。这样anotherActor就不会“看到”MainActor作为发件人。

因此,基本上,您使用forward在中间步骤中发送新消息,但该行中的actor只能响应sender,因为它没有看到中间参与者。

修改:完整的MainActor

class MainActor extends Actor {

override def receive: Receive = {

   //delegating some more work to another container
   case d:DoSomething =>
     anotherActor forward DoThis(d)

   // sending a response back to "route"
   case r:DoThisResponse =>
     sender ! Response

    }
}