java 获取现有的或创建新的 akka 演员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16268333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:28:26  来源:igfitidea点击:

Get existing or create new akka actor

javaakkaactor

提问by Hako

I'm trying to get an existing ActorRef with ActorFor or create a new one if it does not exists. I have the following code but it doesn't seem to work as expected. .isTerminated() is always true.

我正在尝试使用 ActorFor 获取现有的 ActorRef ,或者如果它不存在则创建一个新的。我有以下代码,但它似乎没有按预期工作。.isTerminated() 始终为真。

ActorSystem system = ActorSystem.create("System");

            ActorRef subscriberCandidate = system.actorFor("akka://System/user/"+name);

            if (subscriberCandidate.isTerminated())
            {
                ActorRef subscriber = system.actorOf(new Props(new UntypedActorFactory() {
                      public UntypedActor create() {
                        return new Sub(name,link);
                      }
                    }), name);
                System.out.println(subscriber.path().toString() + " created");
            }
            else
                System.out.println("already exists"); 

What am I missing here? Thanks in advance.

我在这里错过了什么?提前致谢。

回答by Roland Kuhn

Get-or-create can only be performed by the parentof the designated actor, since only that parent can create the actor if it does not exist, and only the parent can do so consistently (i.e. without race conditions). Within an actor you can do

Get-or-create 只能由指定actor的父级执行,因为如果actor 不存在,则只有该父级才能创建actor,并且只有父级才能始终如一地这样做(即没有竞争条件)。在一个演员中,你可以做到

// assuming a String name like "fred" or "barney", i.e. without "/"
final Option<ActorRef> child = child(name);
if (child.isDefined())
  return child.get();
else
  return getContext().actorOf(..., name);

Do not do this at the top-level (i.e. using system.actorOf), because then you cannot be sure who “wins” in requesting creation and also relying on the user guardian is not good a good supervision strategy.

不要在顶层(即使用system.actorOf)这样做,因为那样你就无法确定谁在请求创建时“获胜”,并且依赖用户监护人并不是一个好的监督策略。

回答by cmbaxter

Change your lookup to be:

将您的查找更改为:

system.actorFor("/user/" + name)

You don't need the "akka://System" part if this is a local actor you are looking up. This is assuming that this actor was already started up elsewhere in your code though. If not it won't work.

如果这是您要查找的本地演员,则不需要“akka://System”部分。这是假设这个角色已经在你的代码中的其他地方启动了。如果没有它就行不通。

回答by sourcedelica

Based on the given code you are calling actorForto look up a non-existent actor. The actor doesn't exist until actorOfis called.

根据您调用的给定代码actorFor来查找不存在的演员。演员不存在,直到actorOf被调用。