2014-05-01 100 views
2

我對阿卡非常陌生。我用它創建了一個簡單的Hello World應用程序。該應用程序非常簡單,它向我簡單的演員發送消息。我想要的是將消息發回給消息的第一個發件人。我無法得到回覆消息。人怎麼能這樣做?客戶是否必須實施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"); 
     } 

    } 
+0

你應該用 「問」,以獲得一個'Future',而不是 「說」在你的主要方法 – Mik378

+0

非常感謝。我只是使用了一個未來,它的工作。我無法用正確的實施來回答我的問題,但我會。 – SamTheGoodOne

+0

不客氣:) – Mik378

回答

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

    } 

}