8

我正在使用 akka-http 1.0,我想使用定义为的路由

def route: Route = path("") {
  // start actor with requestContext
  // call requestContext.complete(...) in actor with the result
}

我该如何做到这一点?

4

2 回答 2

8

详细说明 @jrudolph 的评论,以下代码满足您将 RequestContext 值分派给 Actor 的要求。您的问题表明您希望每个请求都有一个新的 Actor;但是,下面的代码对所有请求使用相同的 Actor,我认为这是一个更有效/可能的用例。如果需要,Actor 创建始终可以在 handleRequest 中移动。

首先,我们需要一个 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

现在创建一个用于查询 Actor 的实用函数:

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
于 2015-10-29T12:41:21.217 回答
2

你可以尝试更好,比如:

package controllers

import akka.actor.{Actor, ActorSystem, Props}
import akka.stream.ActorMaterializer

import scala.concurrent.{Await, Future}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import akka.pattern.ask
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn
import akka.actor._

import akka.util.Timeout


case object Message

class TestActor(name:String) extends Actor {
  def receive = {
    case Message =>
      sender ! "Testing Ask pattern Approach"
      println(s"hello from $name")

    case _ =>

      println("that was unexpected")
  }
}

object AskTest extends App {

  implicit val system= ActorSystem("myactor")
  implicit val material=ActorMaterializer()

//  implicit val props=Props.empty
implicit val timeout = Timeout(5 seconds)
  implicit val result =system.actorOf(Props(new TestActor("TestingName")),name = "Scala")

   val future3:Future[String]= ask(result ,Message).mapTo[String]
  val results = Await.result(future3, 2 seconds)
  println(results)
}
于 2017-07-05T09:29:09.570 回答