I'm just beginning with AKKA and have a basic question about how non-actor code talks to actor code.
How can non-actor code call an actor and get a response ? I've tried calling the actor from the non-actor using Patterns.ask
but this doesn't work because there is no 'sender' to which the actor can respond.
So how am I supposed to do it ?
This should work just fine. When you use ask
, a lightweight actor (I believe represented by a PromiseActorRef
) is created to represent the sender so that a response can be sent back that will complete the Future
that is created via ask
. A little example to show this in action. First the test actor:
class TestActor extends UntypedActor{
public TestActor(){
}
public void onReceive(Object msg){
getContext().sender().tell("bar", getContext().self());
}
}
Then the non-actor 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With