我正在使用akka-http 1.0,我想使用定义为的路由
def route: Route = path("") { // start actor with requestContext // call requestContext.complete(...) in actor with the result }
我该如何做到这一点?
解决方法
在阐述@jrudolph的注释时,下面的代码满足了将RequestContext值分派给Actor的要求.您的问题表明您希望每个请求都有一个新的Actor;但是,下面的代码对所有请求使用相同的Actor,我认为这是一个更有效/可能的用例.如果需要,可以始终在handleRequest内移动Actor创建.
首先,我们需要一个Actor来处理对响应的请求:
import akka.actor.Actor import akka.http.scaladsl.server.{RequestContext,RouteResult} import akka.http.scaladsl.model.HttpResponse class RequestActor extends Actor { //business logic - returns empty HttpResponse def handleRequestMessage(requestContext : RequestContext) = RouteResult.Complete(new HttpResponse()) override def receive = { case reqContext : RequestContext => sender ! handleRequestMessage(reqContext) } }//end class RequestActor
import akka.actor.ActorRef import scala.concurrent.Future import akka.pattern.ask object RequestActor { val handleRequest : ActorRef => RequestContext => Future[RouteResult] = (actorRef) => (requestContext) => ask(actorRef,reqContext).mapTo[RouteResult] }
import akka.actor.{ActorSystem,Props} import akka.stream.ActorMaterializer import akka.http.scaladsl.Http import akka.http.scaladsl.server.Directives.{get,path} import akka.util.Timeout object RouteActorTest extends App { implicit val as = ActorSystem("RouteActorTest") implicit val timeout = new Timeout(1000) val sendRequestToActor : RequestContext => Future[RouteResult] = RequestActor handleRequest (as actorOf Props[RequestActor]) val route = path("")(get(sendRequestToActor)) //rest of application... }//end object RouteActorTest