Udemy-akka-essential # 05 Actors, Messages and Behaviors

Ada·2023년 10월 4일

Akka

목록 보기
25/32

액터 시스템은 내부적으로 다수의 스레드를 제어하는 무거운 데이터 구조이다.

애플리케이션 인스턴스당 하나의 액터 시스템을 갖는것이 좋다.

액터 시스템의 이름에는 영어와 숫자만 포함되어야 한다.

액터는 액터 시스템 내에서 고유하게 식별된다.

메시지는 비동기적으로 전달되고 처리된다.

각 액터는 고유한 행동이나 메시지 처리방식을 갖고 있다.

다른 액터를 침범하거나 그들의 마음을 읽거나 다른 방법으로 원하는 정보를 강제로 주게 할 수 없다.

Akka 에서 액터와 일반 객체의 차이점은 액터는 인스턴스화 할 수 없다는 것이다.
(new 를 호출하는 것이 아니라, 액터 시스템을 호출함)

액터는 캡슐화 되기 때문에 해당 메서드를 호출할 수 없으며, 액터 클래스를 직접 인스턴스화 할 수 없다. 따라서 액터 참조를 사용해야 한다.

추가적인 학습 내용은 주석 안에 있다.

package part2actors

import akka.actor.{Actor, ActorSystem, Props}

object ActorsIntro extends App {

  // part1 - actor systems
  val actorSystem = ActorSystem("firstActorSystem")
  println(actorSystem.name)

  // part2 - create actors
  // word count actor
  // 클래스 선언으로 액터 생성
  class WordCountActor extends Actor {
    // internal data
    var totalWords = 0

    // behavior
    // def receive: PartialFunction[Any,Unit] -> 인수 안 받고 반환 유형은 두 단위의 부분 함수
    def receive: Receive = {
      case message: String =>
        println(s"[word counter] I have received: $message")
        totalWords += message.split(" ").length
      case msg => println(s"[word counter] I cannot understand ${msg.toString}")
    }
  }

  // part3 - instantiate our actor
  // 액터는 new 인스턴스로 선언하지 않고 액터 시스템을 호출한다.
  // 액터 시스템을 통해 액터 호출 후 인스턴스화 하려는 액터 유형으로 입력된 props 객체 전달
  val wordCounter = actorSystem.actorOf(Props[WordCountActor], "wordCounter")
  val anotherWordCounter = actorSystem.actorOf(Props[WordCountActor], "anotherWordCounter")

  // part4 - communicate!
  wordCounter ! "I am learning Akka and it's pretty damn cool!" // "tell"
  anotherWordCounter ! "A different message"
  // asynchronous!

  
  // 생성자 인수를 사용하여 액터를 생성하는 가장 좋은 방법
  // object Person : 컴패니언 객체
  // 컴패니언 객체를 정의하고 일부 인수를 기반으로 props 객체를 생성하는 메서드를 정의함
  object Person {
    def props(name: String) = Props(new Person(name))
  }

  class Person(name: String) extends Actor {
    override def receive: Receive = {
      case "hi" => println(s"Hi, my name is $name")
      case _ =>
    }
  }

  val person = actorSystem.actorOf(Person.props("Bob"))
  person ! "hi"
}
profile
백엔드 프로그래머

0개의 댓글