Я пытаюсь выяснить, как я могу настроить Master Actor, который вызывает соответствующих детей, в поддержку некоторых маршрутов распыления, где я пытаюсь подражать вызовам db. Я новичок в akka/spray, поэтому просто пытаюсь лучше понять, как правильно настроить спрей -> актеры -> вызовы db (и т. Д.). Я могу получить ответ от актера верхнего уровня, но когда я пытаюсь вернуть его с одного уровня актера ниже родителя, я не могу заставить ничего работать.Spray route получить ответ от дочернего актера
При взгляде на пути актеров кажется, что из-за того, что я делаю звонок от моего маршрута распыления, я перехожу от временного актера. Ниже приводится то, что я имею до сих пор для этого. Это должно быть просто ошибкой пользователя/незнанием, просто не уверен, как действовать. Мы ценим любые предложения.
Demo Spray Service и Redis Ниже перечислены фрагменты кода Actor, где я вызываю актера с моего маршрута и нескольких участников, у которых возникает проблема (хочу, чтобы мой маршрут получил ответ от SummaryActor). Благодаря!
загрузки:
object Boot extends App {
// we need an ActorSystem to host our application in
implicit val system = ActorSystem("on-spray-can")
// create and start our service actor
val service = system.actorOf(Props[DemoServiceActor], "demo-service")
implicit val timeout = Timeout(5.seconds)
// start a new HTTP server on port 8080 with our service actor as the handler
IO(Http) ? Http.Bind(service, interface = "localhost", port = 8080)
}
Demo Сервис Актер (для спрея)
class DemoServiceActor extends Actor with Api {
// the HttpService trait defines only one abstract member, which
// connects the services environment to the enclosing actor or test
def actorRefFactory = context
// this actor only runs our route, but you could add
// other things here, like request stream processing
// or timeout handling
def receive = handleTimeouts orElse runRoute(route)
//Used to watch for request timeouts
//http://spray.io/documentation/1.1.2/spray-routing/key-concepts/timeout-handling/
def handleTimeouts: Receive = {
case Timedout(x: HttpRequest) =>
sender ! HttpResponse(StatusCodes.InternalServerError, "Too late")
}
}
//Master trait for handling large APIs
//http://stackoverflow.com/questions/14653526/can-spray-io-routes-be-split-into-multiple-controllers
trait Api extends DemoService {
val route = {
messageApiRouting
}
}
Demo Spray Service (Route):
trait DemoService extends HttpService with Actor {
implicit val timeout = Timeout(5 seconds) // needed for `?` below
val redisActor = context.actorOf(Props[RedisActor], "redisactor")
val messageApiRouting =
path("summary"/Segment/Segment) { (dataset, timeslice) =>
onComplete(getSummary(redisActor, dataset, timeslice)) {
case Success(value) => complete(s"The result was $value")
case Failure(ex) => complete(s"An error occurred: ${ex.getMessage}")
}
}
def getSummary(redisActor: ActorRef, dataset: String, timeslice: String): Future[String] = Future {
val dbMessage = DbMessage("summary", dataset + timeslice)
val future = redisActor ? dbMessage
val result = Await.result(future, timeout.duration).asInstanceOf[String]
result
}
}
Redis Актер (Mock никакого фактического Redis клиент еще)
class RedisActor extends Actor with ActorLogging {
// val pool = REDIS
implicit val timeout = Timeout(5 seconds) // needed for `?` below
val summaryActor = context.actorOf(Props[SummaryActor], "summaryactor")
def receive = {
case msg: DbMessage => {
msg.query match {
case "summary" => {
log.debug("Summary Query Request")
log.debug(sender.path.toString)
summaryActor ! msg
}
}
}
//If not match log an error
case _ => log.error("Received unknown message: {} ")
}
}
class SummaryActor extends Actor with ActorLogging{
def receive = {
case msg: DbMessage =>{
log.debug("Summary Actor Received Message")
//Send back to Spray Route
}
}
}
спасибо тонну. Я рассмотрю предлагаемые обновления. Благодаря! – scarpacci
Работали как обаяние на обоих счетах. Еще раз спасибо. – scarpacci