【发布时间】: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 的书籍,其中大多数都太大了。我会毫不犹豫地买这个。再次感谢迈克!