Calling an actor on a spray track and waiting for an Actor's response

After using Play! A framework for a while, I will first look at Spray. I started with the sample I found on GitHub, now I want to change it, but it's not easy for me to understand how this works.

How can I wait for a message from an actor in the code below?

package api import akka.actor.ActorRef import scala.concurrent.ExecutionContext import spray.routing.Directives import core.ClassifierActor class ClassifierService(classifier: ActorRef)(implicit executionContext: ExecutionContext) extends Directives with DefaultJsonFormats { import ClassifierActor._ implicit val classifyMessageFormat = jsonFormat4(ClassifyMessage) val route = path("classify") { post { handleWith { // The ClassifierActor gets a ClassifyMessage and // sends a ClassifiedMessage back to the sender. // How can wait for the ClassifiedMessage here // and send a HttpResponse back? cm: ClassifyMessage => classifier ! cm // ??? } } } } 
+5
source share
2 answers

Spray is already based on akka.io

That way, if you just want to complete your route with an actor’s reaction, you can use a query template

 import akka.pattern.ask import scala.concurrent.duration._ implicit val timeout = Timeout(5 seconds) // needed for `?` below val route = path("classify") { post { onComplete(actorResponse(yourActor, yourMessage)) { complete(_) } } } def actorResponse[T](actor: ActorRef, msg: ClassifyMessage): Future[T] = (actor ? msg).mapTo[T] 

If you want to redirect a request to your model of your actor and complete the route somewhere in the acting system, you need to send RequestContext to the participants. Perhaps this example might help you. Good luck

+12
source

Take a look at my sample project. This service uses Futures to complete routes. As Rup commented, it is bad practice to wait for an answer. Return the future immediately and let it fill when it gets the result.

In your example classifier ! cm classifier ! cm uses the "tell" actor template. It sends a cm message to the classifier actor and proceeds. If you want an answer in the future, use the "ask": classifier ? cm template classifier ? cm classifier ? cm In your cm receiving method, you will return the future with sender ! responseMsg sender ! responseMsg which will return in the future.

+3
source

Source: https://habr.com/ru/post/1204469/


All Articles