简体   繁体   English

获取现有的或创建新的Akka演员

[英]Get existing or create new akka actor

I'm trying to get an existing ActorRef with ActorFor or create a new one if it does not exists. 我正在尝试使用ActorFor获取现有的ActorRef,或者如果不存在则创建一个新的。 I have the following code but it doesn't seem to work as expected. 我有以下代码,但它似乎没有按预期工作。 .isTerminated() is always true. .isTerminated()始终为true。

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. 提前致谢。

Get-or-create can only be performed by the parent of the designated actor, since only that parent can create the actor if it does not exist, and only the parent can do so consistently (ie without race conditions). “获取或创建”只能由指定角色的父级执行,因为只有那个父级(如果不存在)可以创建角色,并且只有父级可以一致地创建(即没有竞争条件)。 Within an actor you can do 在演员中,您可以做

// 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 (ie 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 ),因为那样一来您就不能确定谁在请求创建时“胜出”,并且依赖用户的监护人也不是一个好的监管策略。

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. 如果您正在查找的是本地参与者,则不需要“ akka:// System”部分。 This is assuming that this actor was already started up elsewhere in your code though. 假设该参与者已经在代码中的其他地方启动了。 If not it won't work. 如果没有,那是行不通的。

Based on the given code you are calling actorFor to look up a non-existent actor. 根据给定的代码,您正在调用actorFor来查找不存在的actor。 The actor doesn't exist until actorOf is called. 在调用actorOf之前,actor并不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM