简体   繁体   English

在另一个演员中创建Akka演员

[英]Create Akka actor in another actor

I create an actor A. When I send a message to A, the receive method tries to create an actor B. When I run a piece of code that calls: 我创建了一个演员A。当我向A发送消息时, receive方法尝试创建一个演员B。当我运行一段代码时,该代码调用:

context.system.actorOf(Props[B], "B")

I get an exception: 我有一个例外:

InvalidActorNameException: actor name [B] is not unique!

Do you have any idea why this is happening? 您知道为什么会这样吗?

Actor paths (part of which is the name that you pass to system.actorOf or context.actorOf , if you use the variants of actorOf that take a name) must be unique in an actor system. Actor路径 (如果使用具有名称的actorOf变体,则其路径的一部分是传递给system.actorOfcontext.actorOf的名称)必须是唯一的。 You're probably sending more than one message to actor A: every time actor A receives this message, it tries to create a top-level actor B with the name "B". 您可能向演员A发送了多个消息:演员A每次收到此消息时,它都会尝试创建一个名称为“ B”的顶级演员B。 Either drop the name altogether... 要么完全删除名称...

context.system.actorOf(Props[B])

...or add a unique identifier to the name. ...或在名称中添加唯一标识符。 For example: 例如:

val uuid = java.util.UUID.randomUUID.toString
context.system.actorOf(Props[B], s"B-${uuid}")

As a side note, top-level actors (ie, actors created via system.actorOf ) should be made sparingly, as the documentation advises: 附带说明一下,如文档所建议的那样,应尽量减少使用顶级actor(即通过system.actorOf创建的actor):

Top-level actors are the innermost part of your Error Kernel, so create them sparingly and prefer truly hierarchical systems. 顶级角色是错误内核的最内层部分,因此请谨慎创建它们,并更喜欢真正的分层系统。 This has benefits with respect to fault-handling (both considering the granularity of configuration and the performance) and it also reduces the strain on the guardian actor, which is a single point of contention if over-used. 这在处理错误方面有好处(同时考虑配置的粒度和性能),并且还减轻了对守护程序参与者的压力,如果过度使用,这将是一个争执点。

If your intent is to create an actor B as a child of actor A every time the latter receives a message, then use context.actorOf . 如果您的意图是在每次参与者A收到消息时将其创建为参与者A的子代,请使用context.actorOf

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

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