Akka-Http:如何在请求中使用 Actor?

Ran*_*ize 1 scala akka akka-http

基于 Akka-HTTP 的这个简单代码:

val route =
    pathPrefix("myapp") {
      path("search") {
        get {
          //ref ! DoSomething("foo")
          complete(HttpEntity(ContentTypes.`application/json`, /* content here from an actor */ ))
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

如何从 Actor ( sender ! content)返回值?

Tyt*_*yth 5

使用ask模式并映射它的返回未来。

import akka.pattern.ask    // enable `?`
import context.dispatcher  // Future's need an execution context, we use the Actor#context's one 

(ref ? DoSomething("foo")).mapTo[ReturningType].map { result =>
  complete(HttpEntity(ContentTypes.`application/json`, result ))
}
Run Code Online (Sandbox Code Playgroud)