Actor responding to a non-actor

I am just starting with AKKA and asking a basic question about how inactive code talks about actor code.

How can inactive code call an actor and get an answer? I tried calling an actor from a non-actor using Patterns.ask , but this does not work because there is no β€œsender” to which the actor can respond.

So how should I do this?

+4
source share
1 answer

This should work fine. When you use ask , a light entity is created to represent the sender (I believe it is represented by PromiseActorRef ), so that the answer can be sent back, which will complete Future , which is created through ask . A small example to show this in action. First tested actor:

 class TestActor extends UntypedActor{ public TestActor(){ } public void onReceive(Object msg){ getContext().sender().tell("bar", getContext().self()); } } 

Then inactive code that will call it

 import java.util.concurrent.TimeUnit; import scala.concurrent.Await; import scala.concurrent.Future; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.pattern.Patterns; import akka.util.Timeout; public class AskTest { public static void main(String[] args) throws Exception{ ActorSystem sys = ActorSystem.apply("test"); ActorRef ref = sys.actorOf(Props.create(TestActor.class), "mytest"); Timeout t = new Timeout(5, TimeUnit.SECONDS); Future<Object> fut = Patterns.ask(ref, "foo", t); String response = (String)Await.result(fut, t.duration()); System.out.println(response); } } 
+11
source

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


All Articles