如何使用Akka actor来处理Akka中的HTTP请求

时间:2017-05-04 20:09:44

标签: scala akka akka-http

我是Akka HTTP和Scala的新手。我试图使用Akka actor处理HTTP请求。遇到HTTP请求时,会激活相应的子actor。目前这是我的演员逻辑:

trait CorsDirective extends BasicDirectives { actor: Actor =>

  private def createResponder(requestContext: RequestContext) = {
    context.actorOf(Props(new CorsResponder(requestContext)))
  }

  val corsRoute = {
    path("corsdirective") {
      get {
        requestcontext =>
          val corsresponder = createResponder(requestcontext)
          corsresponder ! "corsdirectiveactiviated"
      }
    }
  }
}

class CorsResponder(requestcontext: RequestContext) extends Actor {

  override def receive: Receive = {
    case String => requestcontext.complete("The cors directive was called here")
  }
}

现在我如何插入我的主程序,如下所示:

object AncileService01 extends App {
  val config = ConfigFactory.load()
  val host = config.getString("http.host")
  val port = config.getInt("http.port")

  implicit val system = ActorSystem("My-ActorSystem")
  implicit val executionContext = system.dispatcher
  implicit val materializer = ActorMaterializer()

  val api = corsRoute

  Http().bindAndHandle(api, host, port)
}

1 个答案:

答案 0 :(得分:0)

当您的CorsResponder收到邮件时,您想要回复发件人。所以做这样的事情:

class CorsResponder(requestcontext: RequestContext) extends Actor {

  override def receive: Receive = {
    case String => sender ! "The cors directive was called here"
  }
}

使用ask模式完成您的请求:

import akka.pattern.ask
import context.dispatcher // You will want to pass it to corsRoute as its argument

(corsresponder ? "corsdirectiveactiviated").mapTo[String] { result =>
    case message => complete(message)
}