I would like to implement a little HTTP Server with Scala and Akka. Specifically, I want to have two kind of actor: EmployeeRouterActor and EmployeeEchoActor.
The fisrt one, I want to use it like a router, I mean, that actor receive all messages and it must create an child (in this case, EmployeeEchoActor) for each message.
Each child, it will receive an Employee message and it must give back a string with the employee information.
Moreover, after child complete its process, the child must die. I think the parent is who has to control lifecycle of their children.
In Akka documentation, I only see about using a single child, like this
How can I do this? Is there any example or any other documentation from Akka site?
Something like this:
object EmployeeRouterActor {
final case class Employee(id: String, name: String)
final case object StopChild
final case class ChildResponse(id: String, data: String)
}
final class EmployeeRouterActor extends Actor {
import EmployeeRouterActor._
// Make a map which will store child actors
private var children = Map.empty[String, ActorRef]
override def receive: Receive = {
case e @ Employee(id, _) => getChild(id) ! e
case ChildResponse(id, _) => stopChild(id)
}
// Check whether child exists in context of this actor.
// If it doesn't, create new one.
private def getChild(id: String): ActorRef =
context.child(id).getOrElse {
val child = context.actorOf(EmployeeEchoActor.apply(), id)
children += (id -> child)
child
}
private def stopChild(id: String) = {
children(id) ! StopChild
children -= id
}
}
object EmployeeEchoActor {
def apply(): Props = Props(new EmployeeEchoActor)
}
final class EmployeeEchoActor extends Actor {
// self.path.name to access its id
override def receive: Receive = {
case EmployeeRouterActor.Employee =>
// do stuff with Employee message...
context.parent ! EmployeeRouterActor.ChildResponse(self.path.name, "Done!") // Or pipeTo(context.parent)
case EmployeeRouterActor.StopChild => context.stop(self)
}
}
Basically, child actors are created and stored in a Map
. When they finish their tasks, they reply with the response message to their parent which then stops them.