三种了解 akka actor 存在的方法

10
我正在使用akka actors(JAVA),最近了解到有3种(可能更多)了解actor是否存在的方法。
  1. 发送Identify消息

    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: 创建另一个actor,调用getContext().watch(ActorRef of actorToWatch);并检查是否接收了Terminated消息。这只能用于已经创建的actor。

第1和2点告诉我们演员的存在,第3点监控。我想知道这三个的使用情况以及它们对演员邮件箱和功能的影响,以便我可以选择适合我的应用程序的类型。

检查演员是否存在是一个好习惯吗?如果不是,为什么?


1
通常,在Akka代码库中需要知道演员是否存在是一种代码异味。 - Ryan
在你的第一个例子中,变量 timeOut 是指什么? - KJ50
timeOut是等待响应的时间(Timeout timeOut = new Timeout(5, TimeUnit.SECONDS))。 - achuth
1个回答

5

好的,只有一种方法可以知道一个Actor是否在过去的某个时间点存在:如果你收到了来自它的消息。以上所有内容都是基于此主题的变化。

话虽如此,一旦你有了ActorRef,就可以使用DeathWatch来被通知该actor的终止。但是还没有收到Terminated消息并不意味着该actor仍然存活:Terminated可能已经在路上了。

把Actor看作只能通过发送电子邮件来交流的人。这个类比对于他们交互的语义非常适用。


感谢@Roland Kuhn提供的“只有一种方法可以知道在过去某个时间点是否存在Actor”的建议。 - achuth
我认为上述每个功能都可以在不向actor发送消息的情况下工作,因此最终所有这些功能只是向actor发送和接收消息。 - achuth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接