简体   繁体   中英

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. 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. 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:

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. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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