Udemy-akka-essential #09 Child Actors 1

Ada·2023년 11월 8일

Akka

목록 보기
31/32

액터가 자식 액터를 만드는 것에 대해 공부했다.
우선은 아주 기본적으로 구현 할 수 있는 부모-자식 액터만 구현해 봤다.

메시지를 서로 주고받고 결과창에 경로가 변경되어 적히는 것이 새삼 재밌었다.

// 구현 가능한 가장 간단한 액터 예시

import akka.actor.Actor

object ChildActors extends App {

  object Parent {
    case class CreateChild(name: String)
    case class TellChild(message: String)
  }
  class Parent extends Actor {
    import Parent._
    
    var child: ActorRef = null
    
    // 필수 구현 아님
    override def receive: Receive = {
      case CreateChild(name) => 
        println(s"${self.path} creating child")
        // 액터의 메시지 수신 핸들러 내에서 새로운 액터 만들기
        // val childRef = context.actorOf(Props[Child], name)
        // child = childRef // 하위 멤버를 하위 참조로 할당
        val childRef = context.actorOf(Props[Child], name)
        cotext.become(withChild(childRef) // 새로운 메시지 핸들러 호출
	  // 새로운 메시지 핸들러의 일부가 될 것, withChild 로 옮김
      // case TellChild(message) => 
        // if (child != null) child forward message
    }
    
    def withChild(childRef: ActorRef): Receive = {
      case TellChild(message) => childRef forward message 
    }
  }
  
  class Child extends Actor {
    overrid def receive: Receive = {
      case message => println(s"${self.path} I got: $message")
    }
  }
  import Prent._
  
  val system = ActorSystem ("ParentChildDemo")
  val parent = system.actorOf(Props[Parent], "parent")
  parent ! CreateChild("child")
  parent ! TellChild("hey kid!")
  
  // result
  akka://ParentChildDemo/user/parent creating child // 부모 경로
  akka://ParentChildDemo/user/parent/child I got: hey Kid! // 자식 경로
}

profile
백엔드 프로그래머

0개의 댓글