2014-04-28 22 views
9

我正在做akka演员(JAVA),最近才知道有3种方法(可能更多)知道演员的存在。知道akka演员存在的三种方法

  1. 发送识别消息

    ActorSelection sel = actorSystem.actorSelection("akka://test/user/TestActor"); 
    AskableActorSelection asker = new AskableActorSelection(sel); 
    Future<Object> future = asker.ask(new Identify(1), new Timeout(5, 
         TimeUnit.SECONDS)); 
    ActorIdentity identity = (ActorIdentity) Await.result(future, timeOut.duration()); 
    ActorRef reference = identity.getRef(); 
    if(reference != null){ 
        // Actor exists 
    } else { 
    // Actor does not exits 
    } 
    
  2. resolveOne方法

    ActorSelection sel = actorSystem.actorSelection("akka://test/user/TestActor"); 
    Future<ActorRef> future = sel.resolveOne(new Timeout(5, 
         TimeUnit.SECONDS)); 
    // Wait for the completion of task to be completed. 
    future.onComplete(new OnComplete<ActorRef>() { 
        @Override 
        public void onComplete(Throwable excp, ActorRef child) 
          throws Throwable { 
         // ActorNotFound will be the Throwable if actor not exists 
         if (excp != null) { 
           // Actor does not exists 
         } else { 
          // Actor exits 
         } 
        } 
    }, actorSystem.dispatcher()); 
    
  3. DeatchWatch: 创建另一个演员电话getContext()。watch(ActorToWatch的ActorRef);并检查收到的已终止消息。这可能仅用于已经创建的actor。

1,2告诉演员和3个监视器的存在。我想知道这三个用例以及它们对演员信箱和功能的影响,以便我可以选择适合我的应用程序的类型。

正在检查演员的存在是一种好的做法吗?如果不是为什么?

+1

通常,需要知道演员是否存在是Akka代码库中的代码异味。你的第一个例子中的 – Ryan

+0

,变量'timeOut'指的是什么? – KJ50

+0

超时是等待时间响应(timeout超时=新的超时(5 TimeUnit.SECONDS)) – achuth

回答

4

那么,只有一种方法可以知道Actor是否存在于过去的某个时间点:如果您收到来自它的消息。以上所有仅仅是这个主题的变体。

也就是说,一旦你有了ActorRef,你就可以使用DeathWatch来通知该演员的终止。但尚未收到终止消息并不意味着演员仍然活着:终止已经可能已经开始。

认为演员是只能通过发送电子邮件进行沟通的人。这种比喻对于他们互动的语义来说非常有效。

+0

感谢@Roland库恩的“只有一个办法知道一个演员是否在过去的某个点存在”,” – achuth

+0

我想每个上述功能在没有向演员发送消息的情况下工作,因此最终所有上述工作仅向演员发送和接收消息。 – achuth