向发件人发送返回消息并将其打印出来

时间:2014-05-01 12:46:41

标签: java akka

我是阿卡的新手。我用它创建了一个简单的Hello World App。 该应用程序非常简单,它向我的简单Actor发送消息。我想要的是将消息发送回消息的第一个发件人。我无法收到回复消息。有人怎么做到这一点?客户端是否必须实现onReceive方法?我试图在代码中发表评论。

import akka.actor.UntypedActor;

    public class HelloActor extends UntypedActor {
        @Override
        public void onReceive(Object o) throws Exception {
            if(o instanceof String){
                String message = (String)o;
                System.out.println(message);
                // how to get this response ? 
                getSender().tell("World",getSelf());
            }
        }
    }

客户

import akka.actor.ActorRef;
    import akka.actor.ActorSystem;
    import akka.actor.Props;

    public class Client{

        public static void main(String[] args){
            ActorSystem actorSystem = ActorSystem.create("HelloWorldSystem");

            ActorRef listener = actorSystem.actorOf(new Props(HelloActor.class), "listener");
            // sending is OK but how to get the response?
            listener.tell("Hello");
        }

    }

1 个答案:

答案 0 :(得分:1)

正确的答案是使用未来:

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.dispatch.*;
import akka.dispatch.Future;
import akka.pattern.Patterns;
import akka.util.Duration;
import akka.util.Timeout;

public class Client{

    public static void main(String[] args){
        ActorSystem actorSystem = ActorSystem.create("HelloWorldSystem");
        ActorRef listener = actorSystem.actorOf(new Props(HelloActor.class), "listener");

        Timeout timeout = new Timeout(Duration.create(5, "seconds"));
        Future<Object> future = Patterns.ask(listener, "Hello", timeout);

        try{
            String result = (String) Await.result(future, timeout.duration());
            System.out.println(result);

        }catch (Exception e){
            e.printStackTrace();
        }

    }

}