import akka.actor.{Actor, ActorRef, ActorSystem, Props}
object AkkaMain {
object Parent {
def props() = Props(new Parent())
case class CreateChild(name: String)
case class TellChild(message: String)
}
import Parent.{CreateChild, TellChild}
class Parent extends Actor {
override def receive: Receive = {
case CreateChild(name) =>
println(s"${self.path} creating child")
val childRef = context.actorOf(Child.props(), name)
context.become(withChild(childRef))
}
def withChild(childRef: ActorRef): Receive = {
case TellChild(message) =>
if (childRef != null) childRef forward message
}
}
object Child {
def props() = Props(new Child())
}
class Child extends Actor {
override def receive: Receive = { case message =>
println(s"${self.path} I got: $message")
}
}
def main(args: Array[String]): Unit = {
val actorSystem: ActorSystem = ActorSystem(name = "actorDemo")
import Parent._
val parentActor = actorSystem.actorOf(Parent.props(), "parent")
parentActor ! CreateChild("child")
parentActor ! TellChild("hey Kid!")
val childSelection = actorSystem.actorSelection("/user/parent/child")
childSelection ! "I found you"
}
}
결과
akka://actorDemo/user/parent creating child
akka://actorDemo/user/parent/child I got: hey Kid!
akka://actorDemo/user/parent/child I got: I found you
설명
- context.actorOf() 로 child actor 생성
- parent / child actor 로 tree heirachy 를 구성할 수 있다.
- top-level supervisor (guardians)
- / : the root guardian
- /system: logging 등 ..
- /user: application 에서 생성하는 actor
- actorSystem.actorSelection() 으로 actor 에 접근할 수 있다.
- 주의 사항
- parent actor 의 상태 변수나 parent `this` 를 절대 child actor 로 전달하지 말라!
- actor 의 상태는 override def receive: Receive 메소드를 통해서만 관리되어야 한다.