简体   繁体   English

Akka演员和消息处理

[英]Akka Actors and Message Handling

I have an ActorSystem where I create one top level actor and in this top level actor, I create a couple of child actors. 我有一个ActorSystem,其中创建了一个顶级演员,在这个顶级演员中,我创建了几个子演员。 So far good! 到目前为止很好!

What I then do is to expose these child actors to my Application controller (in a Play application) so that I can directly pipe the messages intended for the corresponding child actor from my Play controller. 然后,我要做的是将这些子actor暴露给我的Application控制器(在Play应用程序中),以便我可以直接从Play控制器中通过管道传递用于相应子actor的消息。 Is this a good practice or should I always pipe the messages to the child actor via the supervisor? 这是一种好习惯吗,还是我应该始终通过主管将消息通过管道传递给子演员? In code, it would look like below: 在代码中,如下所示:

class Application extends Controller with MyActors {

  def createUser = { request =>
    val user: User = ... get the User from the request body
    userActor ! user
  }
}

Here is what my Supervisor Actor looks like and it is controlled by the Play applications lifecycle plugin: 这是我的Supervisor Actor外观,它由Play应用程序生命周期插件控制:

class SupervisorActor extends Actor with ActorLogging {

  val allActors = MyActors(context.system.settings.config, context)

  context watch allActors.userActor

  // TODO: what should we do in this SupervisorActor?
  def receive = {
    case Terminated(terminate) => context stop self
    case _ =>
  }
}

I then inject this MyActors into the Play Application controller. 然后,我将此MyActors注入到Play Application控制器中。 So my question, is this a good approach? 所以我的问题是,这是一个好方法吗? The child actors are receiving messages directly from the outside world, without the messages having to go through the Supervisor actor. 子演员直接从外界接收消息,而消息不必通过主管演员。 Is this a good approach. 这是一个好方法。 What problems could I face with this approach? 这种方法会遇到什么问题?

There is nothing inherently bad or good about your approach. 您的方法本质上没有坏处。 Some problems call for direct communication with the child Actors and some call for using the supervisor. 有些问题要求与子Actor直接沟通,有些要求使用主管。

I would say instances where contacting the supervisor is beneficial is if you need some type of routing logic, eg 1 message gets broadcasted to all child Actors or routing based on the contents of the message. 我想说,如果需要某种路由逻辑,那么与主管联系是有利的,例如,一条消息广播给所有子Actor或基于消息的内容进行路由。

On the other hand it may be better to directly contact the children if the supervisor has other responsibilities and you want to distribute the work load. 另一方面,如果主管有其他职责并且您要分配工作量,则最好直接与孩子联系。

I personally tend to communicate only with supervisors since it allows for a "single door" approach. 我个人倾向于只与主管沟通,因为它允许“单门”方法。 It is also usually easier to dependency inject the supervisor in other areas of the code, that way you don't have to go looking up the child ActorRef. 通常,在代码的其他区域中依赖注入主管也通常更容易,这样您就不必查找子ActorRef。

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

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