[英]How to use Akka actors to handle HTTP requests in Akka
I am new to Akka HTTP and Scala in general. 我是Akka HTTP和Scala的新手。 I was trying to handle HTTP requests using Akka actors. 我试图使用Akka actor处理HTTP请求。 When the HTTP request is encountered, the corresponding child actor gets activated. 遇到HTTP请求时,将激活相应的子actor。 Currently this is my actor logic: 目前,这是我的演员逻辑:
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")
}
}
Now how do I plug into my main program, which is like this: 现在如何插入主程序,如下所示:
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)
}
When your CorsResponder
receives a message, you want to reply to sender. 当您的CorsResponder
收到消息时,您想回复发件人。 So do something like this: 所以做这样的事情:
class CorsResponder(requestcontext: RequestContext) extends Actor {
override def receive: Receive = {
case String => sender ! "The cors directive was called here"
}
}
Use ask
pattern to complete your request: 使用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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.