【问题标题】:Send A Return Message To The Sender And Simply Print It Out向发件人发送返回消息并简单地打印出来
【发布时间】:2014-05-02 18:17:57
【问题描述】:

我对 Akka 很陌生。我使用它创建了一个简单的 Hello World 应用程序。 该应用程序非常简单,它向我的简单 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");
        }

    }

【问题讨论】:

  • 您应该使用“ask”来获得Future,而不是在您的主要方法中使用“tell”
  • 非常感谢。我刚刚使用了 Future 并且它起作用了。我还不能用正确的实现来回答我的问题,但我会的。
  • 所以大多数情况下,在一个actor中运行的所有东西大部分都在它自己的线程中?但不是一直?如果你想在actor之间共享同一个对象会发生什么?
  • 演员本质上确保其代码一次仅由单个线程处理。如果您需要并行化,则需要一个由“路由器”管理的参与者池,以便同时将同一个对象分派给多个参与者。 doc.akka.io/docs/akka/snapshot/java/routing.html
  • 谢谢 我正在浏览有关 akka 的书籍,其中大多数都太大了。我会毫不犹豫地买这个。再次感谢迈克!

标签: java akka


【解决方案1】:

正确答案是使用Future:

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();
        }

    }

}

【讨论】:

    猜你喜欢
    • 2012-12-24
    • 2015-08-18
    • 2012-03-30
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多