콘텐츠 대표 이미지 - Akka를 이용한 Scala 동시성 프로그래밍 완전정복! 🚀

Akka를 이용한 Scala 동시성 프로그래밍 완전정복! 🚀

함께 배우는 액터 모델과 반응형 시스템 구축하기

안녕? 오늘은 Scala와 Akka를 이용한 동시성 프로그래밍에 대해 함께 알아볼 거야! 😊 복잡한 개념들을 최대한 쉽고 재미있게 설명해줄게. 마치 친구랑 대화하듯 편하게 읽어봐!

📚 목차

  1. Akka와 Scala 소개: 왜 함께 쓰는 게 좋을까?
  2. 액터 모델 이해하기: 동시성의 새로운 패러다임
  3. 첫 번째 Akka 애플리케이션 만들기
  4. 액터의 생명주기와 메시지 처리
  5. 액터 계층 구조와 감독 전략
  6. Akka 스트림으로 데이터 흐름 처리하기
  7. 분산 시스템 구축: Akka 클러스터
  8. Akka HTTP로 웹 서비스 개발하기
  9. 실전 프로젝트: 채팅 애플리케이션 만들기
  10. 성능 최적화와 모니터링

1. Akka와 Scala 소개: 왜 함께 쓰는 게 좋을까? 🤔

먼저 Scala와 Akka가 무엇인지, 그리고 왜 이 둘이 찰떡궁합인지 알아보자!

Scala란 무엇인가?

Scala는 객체지향 프로그래밍과 함수형 프로그래밍을 모두 지원하는 JVM 기반 언어야. 2004년에 마틴 오더스키가 개발했고, Java와 완벽하게 호환되면서도 더 간결하고 표현력이 풍부한 문법을 제공해.

Scala의 이름은 'Scalable Language'에서 따왔는데, 작은 스크립트부터 대규모 시스템까지 확장 가능하다는 의미를 담고 있어.

Akka란 무엇인가?

Akka는 JVM 위에서 동시성, 분산, 탄력성을 갖춘 애플리케이션을 쉽게 구축할 수 있게 해주는 툴킷이야. 특히 '액터 모델'이라는 개념을 기반으로 하고 있지.

Akka를 사용하면 멀티스레드 프로그래밍의 복잡성을 크게 줄이면서도 하드웨어 자원을 최대한 활용할 수 있어!

CONCURRENCY BLUEPRINT Scala × Akka 함수형 사고와 액터 모델로 만드는 안정적인 동시성 Scala 함수형 + 객체지향 TYPE SAFE Akka 액터 모델 기반 MESSAGE DRIVEN 비동기 메시징 완벽한 조합 확장성 · 내결함성 · 백프레셔 Scala Akka 확장성 수평 확장 · 비차단 I/O 내결함성 슈퍼비전 · 고립된 실패 백프레셔 수요 주도 스트림 처리

왜 Scala와 Akka를 함께 사용할까?

Scala와 Akka는 서로를 위해 태어난 것 같은 완벽한 조합이야. 그 이유를 살펴보자:

  1. 함수형 프로그래밍의 장점: Scala의 불변성(immutability)과 부수효과 없는 함수는 동시성 프로그래밍에서 발생하는 많은 버그를 방지해줘.
  2. 간결한 문법: Scala의 표현력 있는 문법은 Akka의 액터 모델을 더 간결하게 구현할 수 있게 해줘.
  3. 타입 안전성: Scala의 강력한 타입 시스템은 컴파일 시점에 많은 오류를 잡아내서 더 안정적인 Akka 애플리케이션을 만들 수 있어.
  4. 패턴 매칭: Scala의 패턴 매칭은 Akka 메시지 처리를 매우 직관적으로 만들어줘.
  5. Future와 Promise: Scala의 비동기 프로그래밍 모델은 Akka의 비동기 특성과 자연스럽게 어울려.

실제로 Akka는 Scala로 작성되었고, Scala에서 가장 자연스럽게 사용할 수 있도록 설계되었어. 물론 Java API도 제공하지만, Scala에서 사용할 때 그 진가가 더 발휘된다고 할 수 있지!

요즘 같은 멀티코어 시대에 Scala+Akka 조합은 확장 가능한 백엔드 시스템을 구축하는 데 최적의 선택이야. 재능넷 같은 대규모 플랫폼의 백엔드도 이런 기술로 구축하면 성능과 안정성을 모두 잡을 수 있을 거야!

2. 액터 모델 이해하기: 동시성의 새로운 패러다임 🎭

액터 모델은 1973년 칼 휴이트(Carl Hewitt)가 제안한 수학적 모델로, 동시성 프로그래밍의 복잡성을 해결하기 위한 접근 방식이야. 기존의 스레드와 락(lock) 기반 동시성 모델과는 완전히 다른 패러다임을 제시하지.

액터 모델의 핵심 개념

액터는 동시성의 기본 단위로, 자신만의 상태를 가지고 메시지를 주고받으며 독립적으로 동작해.

액터 모델의 주요 특징은 다음과 같아:

  1. 캡슐화된 상태: 각 액터는 자신만의 상태를 가지며, 이 상태는 외부에서 직접 접근할 수 없어. 오직 메시지를 통해서만 상호작용할 수 있지.
  2. 메시지 기반 통신: 액터들은 오직 메시지를 통해서만 통신해. 이 메시지들은 비동기적으로 전달돼.
  3. 경량 프로세스: 액터는 매우 가벼워서 수백만 개의 액터를 하나의 시스템에서 실행할 수 있어.
  4. 위치 투명성: 액터가 같은 JVM 내에 있든, 다른 서버에 있든 상관없이 동일한 방식으로 통신할 수 있어.
액터 A 액터 B 액터 C 메시지 1 메시지 2 메시지 3 메시지 4 액터 모델: 메시지 기반 비동기 통신 각 액터는 독립적으로 실행되며 메시지를 통해서만 통신합니다

전통적인 스레드 모델 vs 액터 모델

전통적인 멀티스레드 프로그래밍과 액터 모델의 차이점을 비교해보자:

특성 전통적인 스레드 모델 액터 모델
상태 공유 공유 메모리, 락(lock) 필요 상태 격리, 메시지로만 통신
동기화 명시적 동기화 필요 메시지 큐가 자동으로 처리
오류 처리 try-catch로 개별 처리 감독 계층으로 체계적 처리
확장성 스레드 수에 제한 수백만 액터 생성 가능
분산 처리 추가 작업 필요 위치 투명성 내장

Akka에서의 액터 모델

Akka는 JVM 위에서 액터 모델을 구현한 가장 성공적인 프레임워크야. Akka에서 액터는 다음과 같은 특징을 가져:

  1. ActorRef: 액터에 대한 참조로, 직접 액터 인스턴스에 접근하는 것이 아니라 이 참조를 통해 메시지를 보내.
  2. ActorSystem: 액터들의 컨테이너로, 액터의 생성과 생명주기를 관리해.
  3. Dispatcher: 메시지 처리를 위한 스레드 풀을 관리하며, 액터에게 실행 시간을 할당해.
  4. Mailbox: 각 액터는 자신만의 메일박스를 가지며, 여기에 메시지가 큐 형태로 쌓여.
  5. Supervision: 부모 액터가 자식 액터의 오류를 처리하는 계층적 구조를 제공해.

Akka의 액터 모델은 "Let it crash" 철학을 따라. 오류가 발생하면 액터를 재시작하는 방식으로 자가 복구 시스템을 구현할 수 있어!

이런 특성 덕분에 Akka는 고가용성, 고성능 시스템을 구축하는 데 이상적이야. 특히 마이크로서비스 아키텍처나 실시간 데이터 처리 시스템에서 많이 활용되고 있지.

3. 첫 번째 Akka 애플리케이션 만들기 🛠️

이제 실제로 Scala와 Akka를 사용하여 간단한 애플리케이션을 만들어보자! 개발 환경 설정부터 시작할게.

개발 환경 설정

먼저 SBT(Scala Build Tool)를 사용해서 프로젝트를 설정할 거야. SBT는 Scala 프로젝트를 위한 빌드 도구로, Maven이나 Gradle과 비슷한 역할을 해.

다음과 같은 build.sbt 파일을 만들어보자:

name := "akka-hello-world"
version := "1.0"
scalaVersion := "2.13.10"

val akkaVersion = "2.7.0"

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor-typed" % akkaVersion,
  "com.typesafe.akka" %% "akka-stream" % akkaVersion,
  "ch.qos.logback" % "logback-classic" % "1.4.5"
)

이 설정은 Akka의 핵심 라이브러리인 akka-actor-typed와 akka-stream, 그리고 로깅을 위한 logback을 의존성으로 추가하고 있어.

첫 번째 액터 만들기

이제 간단한 인사말을 주고받는 액터를 만들어보자. 먼저 메시지 프로토콜을 정의할게:

package com.example

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.Behaviors

object HelloWorld {
  // 메시지 프로토콜 정의
  sealed trait Command
  final case class Greet(name: String, replyTo: ActorRef[Greeted]) extends Command
  final case class Greeted(name: String, from: ActorRef[Command]) extends Command

  // 액터 행동 정의
  def apply(): Behavior[Command] = Behaviors.receive { (context, message) =>
    message match {
      case Greet(name, replyTo) =>
        context.log.info("Hello {}!", name)
        replyTo ! Greeted(name, context.self)
        Behaviors.same
    }
  }
}

이 코드에서 중요한 부분을 살펴보자:

  1. sealed trait Command: 이 액터가 처리할 수 있는 메시지 타입을 정의해.
  2. case class Greet: 인사 요청 메시지로, 이름과 응답을 받을 액터 참조를 포함해.
  3. case class Greeted: 인사에 대한 응답 메시지야.
  4. apply() 메서드: 이 액터의 행동(Behavior)을 정의하는 팩토리 메서드야.
  5. Behaviors.receive: 메시지를 받아 처리하는 행동을 정의해.
  6. context.log.info: 로그를 남기는 부분이야.
  7. replyTo ! Greeted: '!' 연산자를 사용해 다른 액터에게 메시지를 보내고 있어.
  8. Behaviors.same: 액터의 행동을 변경하지 않고 유지한다는 의미야.

Akka Typed API에서는 액터가 처리할 수 있는 메시지 타입을 명확히 정의해서 타입 안전성을 높여줘!

메인 애플리케이션 만들기

이제 HelloWorld 액터를 사용하는 메인 애플리케이션을 만들어보자:

package com.example

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.Behaviors
import akka.actor.typed.ActorSystem

object HelloWorldApp {
  
  object HelloWorldBot {
    def apply(max: Int): Behavior[HelloWorld.Greeted] = {
      bot(0, max)
    }

    private def bot(greetingCounter: Int, max: Int): Behavior[HelloWorld.Greeted] =
      Behaviors.receive { (context, message) =>
        val n = greetingCounter + 1
        context.log.info("Greeting {} for {}", n, message.name)
        if (n == max) {
          Behaviors.stopped
        } else {
          message.from ! HelloWorld.Greet(message.name, context.self)
          bot(n, max)
        }
      }
  }

  def main(args: Array[String]): Unit = {
    // 액터 시스템 생성
    val system: ActorSystem[HelloWorld.Command] = 
      ActorSystem(HelloWorld(), "HelloSystem")
    
    // HelloWorldBot 생성 및 첫 메시지 전송
    val max = 3
    val bot: ActorRef[HelloWorld.Greeted] = 
      system.systemActorOf(HelloWorldBot(max), "HelloBot")
    
    system ! HelloWorld.Greet("World", bot)
    
    // 프로그램이 바로 종료되지 않도록 대기
    Thread.sleep(3000)
    system.terminate()
  }
}

이 코드에서는 다음과 같은 일이 일어나:

  1. HelloWorldBot이라는 새로운 액터를 정의해. 이 액터는 HelloWorld 액터로부터 인사를 받고, 정해진 횟수만큼 다시 인사를 요청해.
  2. main 메서드에서는 HelloWorld 액터를 루트로 하는 액터 시스템을 생성해.
  3. HelloWorldBot 액터를 생성하고, 첫 번째 Greet 메시지를 HelloWorld 액터에게 보내.
  4. 그러면 HelloWorld와 HelloWorldBot이 서로 인사를 주고받게 돼.
  5. max 횟수에 도달하면 HelloWorldBot은 자신의 행동을 Behaviors.stopped로 변경해 종료돼.

실행 결과

이 프로그램을 실행하면 다음과 같은 결과가 나와:

[INFO] [akka://HelloSystem/user/] - Hello World!
[INFO] [akka://HelloSystem/user/HelloBot] - Greeting 1 for World
[INFO] [akka://HelloSystem/user/] - Hello World!
[INFO] [akka://HelloSystem/user/HelloBot] - Greeting 2 for World
[INFO] [akka://HelloSystem/user/] - Hello World!
[INFO] [akka://HelloSystem/user/HelloBot] - Greeting 3 for World

이렇게 HelloWorld 액터와 HelloWorldBot 액터가 서로 메시지를 주고받으며 통신하는 것을 볼 수 있어. 이것이 Akka의 기본적인 동작 방식이야!

이런 방식으로 복잡한 시스템도 작은 액터들의 조합으로 구성할 수 있어. 각 액터는 독립적으로 동작하면서도 메시지를 통해 협력하지!

실제 프로젝트에서는 이보다 훨씬 복잡한 액터 시스템을 구성하게 될 텐데, 재능넷 같은 플랫폼에서도 사용자 요청 처리, 알림 발송, 결제 처리 등 다양한 기능을 액터로 모델링할 수 있을 거야.

4. 액터의 생명주기와 메시지 처리 🔄

액터는 생성되고, 메시지를 처리하고, 때로는 오류가 발생하기도 하며, 결국에는 종료돼. 이런 액터의 생명주기와 메시지 처리 방식에 대해 자세히 알아보자!

액터의 생명주기

Akka에서 액터의 생명주기는 다음과 같은 상태로 구성돼:

생성 실행 재시작 종료 액터의 생명주기
  1. 생성(Created): 액터가 생성되면 PreStart 훅이 호출돼. 여기서 초기화 작업을 수행할 수 있어.
  2. 실행(Running): 액터가 메시지를 받아 처리하는 상태야.
  3. 재시작(Restarting): 오류가 발생하면 액터는 재시작될 수 있어. 이때 PreRestart와 PostRestart 훅이 호출돼.
  4. 종료(Terminated): 액터가 종료되면 PostStop 훅이 호출돼. 여기서 정리 작업을 수행할 수 있어.

Akka Typed API에서는 이런 생명주기 이벤트를 처리하는 방법이 조금 달라졌어. 다음과 같이 Behaviors.setup을 사용해서 초기화 코드를 작성하고, Behaviors.receiveSignal을 사용해 생명주기 신호를 처리할 수 있지:

def apply(): Behavior[Command] = Behaviors.setup { context =>
  // 초기화 코드 (PreStart에 해당)
  context.log.info("Actor started")
  
  Behaviors.receiveMessage[Command] { message =>
    // 메시지 처리 로직
    Behaviors.same
  }.receiveSignal {
    case (context, PostStop) =>
      // 종료 시 정리 코드 (PostStop에 해당)
      context.log.info("Actor stopped")
      Behaviors.same
  }
}

메시지 처리 방식

액터의 메시지 처리는 다음과 같은 특징을 가져:

  1. 비동기 처리: 메시지는 비동기적으로 전송되며, 발신자는 응답을 기다리지 않아.
  2. 메일박스: 각 액터는 자신만의 메일박스(메시지 큐)를 가지고 있어.
  3. 순차 처리: 한 액터 내에서는 메시지가 순차적으로 처리돼. 이는 동시성 문제를 크게 단순화해.
  4. 메시지 패턴 매칭: Scala의 패턴 매칭을 사용해 다양한 타입의 메시지를 처리할 수 있어.

액터 모델의 핵심은 "한 번에 하나의 메시지만 처리한다"는 원칙이야. 이것이 동시성 문제를 단순화하는 비결이지!

상태 변경과 행동 변경

액터는 메시지를 처리하면서 자신의 상태를 변경할 수 있어. Akka Typed에서는 이를 "행동 변경(behavior change)"이라고 표현해. 다음은 카운터 액터의 예시야:

object Counter {
  sealed trait Command
  case object Increment extends Command
  case object Decrement extends Command
  final case class GetValue(replyTo: ActorRef[Int]) extends Command

  def apply(initialValue: Int): Behavior[Command] = counter(initialValue)

  private def counter(value: Int): Behavior[Command] =
    Behaviors.receive { (context, message) =>
      message match {
        case Increment =>
          context.log.info("Incrementing counter to {}", value + 1)
          counter(value + 1)  // 새로운 상태로 행동 변경
        case Decrement =>
          context.log.info("Decrementing counter to {}", value - 1)
          counter(value - 1)  // 새로운 상태로 행동 변경
        case GetValue(replyTo) =>
          replyTo ! value
          Behaviors.same      // 같은 행동 유지
      }
    }
}

이 예제에서 중요한 부분은:

  1. Increment나 Decrement 메시지를 받으면 counter(새로운 값)을 반환해서 상태를 변경해.
  2. GetValue 메시지를 받으면 Behaviors.same을 반환해서 상태를 유지해.
  3. 상태는 액터 내부에 캡슐화되어 있어서 외부에서 직접 접근할 수 없어.

메시지 응답 패턴

액터 간 통신에서 자주 사용되는 패턴들을 알아보자:

  1. Fire and Forget: 응답을 기대하지 않고 메시지만 보내는 방식이야.
    actorRef ! Message
  2. Request-Response: 응답을 받기 위해 자신의 참조를 메시지에 포함시키는 방식이야.
    actorRef ! Request(context.self)
  3. Ask 패턴: Future를 사용해서 응답을 비동기적으로 처리하는 방식이야.
    import akka.actor.typed.scaladsl.AskPattern._
    import akka.util.Timeout
    import scala.concurrent.duration._
    import scala.concurrent.Future
    
    implicit val timeout: Timeout = 3.seconds
    implicit val scheduler = context.system.scheduler
    
    val result: Future[Response] = actorRef.ask(ref => Request(ref))
            

Ask 패턴은 편리하지만, Future를 다루는 복잡성이 추가돼. 가능하면 액터 모델의 순수한 메시지 패싱 방식을 유지하는 게 좋아!

스테이트풀(Stateful) vs 스테이트리스(Stateless) 액터

액터는 상태를 가질 수도 있고(스테이트풀), 상태가 없을 수도 있어(스테이트리스):

  1. 스테이트풀 액터: 내부 상태를 가지고 있어서 메시지 처리 결과가 이전 상태에 영향을 받아. 위의 Counter 예제가 스테이트풀 액터야.
  2. 스테이트리스 액터: 내부 상태 없이 순수하게 입력 메시지만으로 결과를 결정해. 주로 변환이나 라우팅 같은 작업에 사용돼.

실제 애플리케이션에서는 두 가지 유형을 모두 사용하게 될 거야. 상태 관리가 필요한 부분은 스테이트풀 액터로, 단순 처리 로직은 스테이트리스 액터로 구현하면 돼!

5. 액터 계층 구조와 감독 전략 👨‍👩‍👧‍👦

Akka의 강력한 특징 중 하나는 액터들이 계층 구조를 형성하고, 부모 액터가 자식 액터의 오류를 감독한다는 점이야. 이런 구조가 어떻게 작동하는지 알아보자!

액터 계층 구조

Akka에서 모든 액터는 다른 액터의 자식으로 생성돼. 최상위에는 액터 시스템이 있고, 그 아래로 사용자 액터들이 트리 구조를 형성해:

ActorSystem user childActor1 childActor2 childActor3 액터 계층 구조

액터 계층 구조의 주요 특징은:

  1. 부모-자식 관계: 모든 액터는 부모를 가지며, 자식 액터를 생성할 수 있어.
  2. 생명주기 관리: 부모 액터가 종료되면 모든 자식 액터도 자동으로 종료돼.
  3. 오류 전파: 자식 액터에서 발생한 오류는 부모 액터에게 전달돼.
  4. 위치 투명성: 액터의 경로는 /user/parent/child 형태로 표현되며, 이를 통해 어디서든 액터를 찾을 수 있어.

자식 액터를 생성하는 방법은 다음과 같아:

def apply(): Behavior[Command] = Behaviors.setup { context =>
  // 자식 액터 생성
  val childRef = context.spawn(ChildActor(), "child")
  
  Behaviors.receiveMessage[Command] { message =>
    // 자식 액터에게 메시지 전달
    childRef ! ChildMessage(message)
    Behaviors.same
  }
}

감독 전략(Supervision Strategy)

Akka의 핵심 기능 중 하나는 '감독 전략'이야. 부모 액터는 자식 액터에서 발생한 오류를 처리하는 방법을 정의할 수 있어.

감독 전략은 "Let it crash" 철학을 실현하는 핵심 메커니즘이야. 오류가 발생했을 때 복잡한 복구 로직보다는 액터를 재시작하는 방식으로 시스템의 안정성을 유지해!

Akka Typed에서는 다음과 같은 감독 전략을 제공해:

  1. 재시작(Restart): 오류가 발생한 자식 액터를 재시작해. 상태는 초기화되지만, 액터 자체는 유지돼.
  2. 중지(Stop): 오류가 발생한 자식 액터를 중지시켜.
  3. 에스컬레이션(Escalate): 오류를 부모의 부모에게 전달해.

감독 전략을 설정하는 방법은 다음과 같아:

import akka.actor.typed.SupervisorStrategy

def apply(): Behavior[Command] = Behaviors.setup { context =>
  // 자식 액터에 감독 전략 적용
  val childBehavior = ChildActor()
  val supervisedChild = Behaviors.supervise(childBehavior)
    .onFailure(SupervisorStrategy.restart) // 오류 발생 시 재시작
  
  val childRef = context.spawn(supervisedChild, "supervisedChild")
  
  Behaviors.receiveMessage[Command] { message =>
    // 메시지 처리 로직
    Behaviors.same
  }
}

다양한 예외 유형에 따라 다른 전략을 적용할 수도 있어:

val supervisedChild = Behaviors.supervise(childBehavior)
  .onFailure[IllegalArgumentException](SupervisorStrategy.restart)
  .onFailure[IllegalStateException](SupervisorStrategy.stop)
  .onFailure[RuntimeException](SupervisorStrategy.resume)

오류 처리 예제

실제 오류 처리가 어떻게 작동하는지 예제를 통해 살펴보자:

object WorkerActor {
  sealed trait Command
  case object DoWork extends Command
  case object DoRiskyWork extends Command
  
  def apply(): Behavior[Command] = Behaviors.receiveMessage {
    case DoWork =>
      println("Doing normal work")
      Behaviors.same
    case DoRiskyWork =>
      println("Attempting risky work")
      throw new RuntimeException("Boom! Something went wrong!")
      Behaviors.same
  }
}

object SupervisorActor {
  sealed trait Command
  case object SuperviseWork extends Command
  case object SuperviseRiskyWork extends Command
  
  def apply(): Behavior[Command] = Behaviors.setup { context =>
    // 재시작 전략을 가진 자식 액터 생성
    val supervisedWorker = Behaviors.supervise(WorkerActor())
      .onFailure(SupervisorStrategy.restart)
    
    val workerRef = context.spawn(supervisedWorker, "worker")
    
    Behaviors.receiveMessage {
      case SuperviseWork =>
        context.log.info("Supervising normal work")
        workerRef ! WorkerActor.DoWork
        Behaviors.same
      case SuperviseRiskyWork =>
        context.log.info("Supervising risky work")
        workerRef ! WorkerActor.DoRiskyWork
        Behaviors.same
    }
  }
}

이 예제에서는:

  1. WorkerActor가 DoRiskyWork 메시지를 받으면 예외를 발생시켜.
  2. SupervisorActor는 WorkerActor에 재시작 전략을 적용해.
  3. 예외가 발생하면 WorkerActor는 재시작되고, 작업을 계속할 수 있게 돼.

이런 감독 전략은 분산 시스템에서 특히 중요해. 일시적인 오류가 전체 시스템을 중단시키지 않고, 문제가 있는 부분만 격리하고 복구할 수 있거든!

백오프 감독 전략

반복적인 오류가 발생할 때 유용한 '백오프 감독 전략'도 있어:

import akka.actor.typed.BackoffSupervisorStrategy
import scala.concurrent.duration._

val backoffStrategy = BackoffSupervisorStrategy
  .onFailure(
    minBackoff = 1.second,
    maxBackoff = 30.seconds,
    randomFactor = 0.2,
    maxRestarts = 10
  )

val supervisedChild = Behaviors.supervise(childBehavior)
  .onFailure(backoffStrategy)

이 전략은 오류가 반복될수록 재시작 간격을 점점 늘려서, 시스템에 과부하가 걸리는 것을 방지해. 특히 외부 서비스 연결 같은 작업에서 유용하지!

6. Akka 스트림으로 데이터 흐름 처리하기 🌊

지금까지 개별 메시지를 처리하는 액터에 대해 알아봤어. 하지만 실제 애플리케이션에서는 연속적인 데이터 스트림을 처리해야 할 때가 많아. 이럴 때 Akka Streams를 사용하면 돼!

Akka Streams 소개

Akka Streams는 Reactive Streams 명세를 구현한 라이브러리로, 비동기적이고 논블로킹 방식으로 데이터 스트림을 처리할 수 있어. 특히 다음과 같은 상황에서 유용해:

  1. 대용량 데이터 처리
  2. 백프레셔(backpressure) 관리가 필요한 경우
  3. 데이터 변환 파이프라인 구축
  4. 비동기 I/O 작업

Akka Streams의 핵심 장점은 '백프레셔' 관리야. 생산자가 소비자보다 빠르게 데이터를 생성할 때, 소비자의 처리 능력에 맞춰 데이터 흐름을 조절해줘!

Source Flow Sink Akka Streams 기본 구조 빨간 점선: 백프레셔 신호

Akka Streams의 핵심 컴포넌트

Akka Streams는 세 가지 주요 컴포넌트로 구성돼:

  1. Source: 데이터를 생성하는 컴포넌트. 데이터의 출발점이야.
  2. Flow: 데이터를 변환하는 컴포넌트. 여러 단계의 처리 로직을 구현할 수 있어.
  3. Sink: 데이터를 소비하는 컴포넌트. 데이터의 최종 목적지야.

이 세 컴포넌트를 조합해서 데이터 처리 파이프라인을 구축할 수 있어. 각 컴포넌트는 불변(immutable)이고, 재사용 가능해!

간단한 Akka Streams 예제

먼저 간단한 예제를 통해 Akka Streams의 기본 사용법을 알아보자:

import akka.actor.ActorSystem
import akka.stream.scaladsl._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

implicit val system = ActorSystem("StreamExample")

// 1부터 10까지의 숫자를 생성하는 Source
val source = Source(1 to 10)

// 각 숫자를 제곱하는 Flow
val flow = Flow[Int].map(x => x * x)

// 결과를 출력하는 Sink
val sink = Sink.foreach[Int](x => println(s"결과: $x"))

// Source, Flow, Sink를 연결해서 RunnableGraph 생성
val graph = source.via(flow).to(sink)

// 그래프 실행
val future = graph.run()

// 완료 후 ActorSystem 종료
future.onComplete(_ => system.terminate())

이 예제에서는:

  1. 1부터 10까지의 숫자를 생성하는 Source를 만들어.
  2. 각 숫자를 제곱하는 Flow를 정의해.
  3. 결과를 출력하는 Sink를 만들어.
  4. 이 세 컴포넌트를 연결해서 그래프를 구성하고 실행해.

실행 결과는 다음과 같아:

결과: 1
결과: 4
결과: 9
결과: 16
결과: 25
결과: 36
결과: 49
결과: 64
결과: 81
결과: 100

다양한 Source, Flow, Sink

Akka Streams는 다양한 Source, Flow, Sink를 제공해:

Source의 예:

// 컬렉션에서 Source 생성
val listSource = Source(List("a", "b", "c"))

// 단일 요소 Source
val singleSource = Source.single("element")

// 무한 반복 Source
val tickSource = Source.tick(
  initialDelay = 0.seconds,
  interval = 1.second,
  tick = "tick"
)

// 파일에서 라인 단위로 읽는 Source
val fileSource = StreamConverters.fromInputStream(() => 
  new FileInputStream("data.txt")
)

Flow의 예:

// 맵 변환
val mapFlow = Flow[String].map(s => s.toUpperCase)

// 필터링
val filterFlow = Flow[Int].filter(_ % 2 == 0)

// 평탄화(flatMap)
val flatMapFlow = Flow[String].mapConcat(s => s.toList)

// 비동기 처리
val asyncFlow = Flow[Int].mapAsync(parallelism = 4)(x => 
  Future { 
    Thread.sleep(100) // 시간이 걸리는 작업 시뮬레이션
    x * 2 
  }
)

// 그룹화
val groupedFlow = Flow[Int].grouped(3)

Sink의 예:

// 출력 Sink
val printSink = Sink.foreach[Any](println)

// 무시 Sink
val ignoreSink = Sink.ignore

// 첫 번째 요소만 가져오는 Sink
val headSink = Sink.head[String]

// 리스트로 모으는 Sink
val listSink = Sink.seq[Int]

// 파일에 쓰는 Sink
val fileSink = StreamConverters.fromOutputStream(() => 
  new FileOutputStream("output.txt")
)

실용적인 예제: 파일 처리

실제 상황에서 유용한 파일 처리 예제를 살펴보자:

import akka.actor.ActorSystem
import akka.stream.scaladsl._
import akka.util.ByteString
import java.nio.file.Paths
import scala.concurrent.Future

implicit val system = ActorSystem("FileProcessing")
implicit val ec = system.dispatcher

// 파일에서 라인 단위로 읽기
val source = FileIO.fromPath(Paths.get("input.csv"))
  .via(Framing.delimiter(ByteString("\n"), maximumFrameLength = 1024))
  .map(_.utf8String)
  .drop(1) // 헤더 제외

// CSV 파싱 및 변환
val processFlow = Flow[String]
  .map(line => {
    val columns = line.split(",").map(_.trim)
    (columns(0), columns(1).toInt) // (이름, 나이) 튜플로 변환
  })
  .filter(_._2 >= 18) // 18세 이상만 필터링
  .map { case (name, age) => 
    s"$name is $age years old"
  }

// 결과를 새 파일에 쓰기
val sink = Flow[String]
  .map(s => ByteString(s + "\n"))
  .toMat(FileIO.toPath(Paths.get("output.txt")))(Keep.right)

// 그래프 실행
val result: Future[akka.stream.IOResult] = 
  source.via(processFlow).runWith(sink)

// 완료 후 처리
result.onComplete { res =>
  println(s"파일 처리 완료: $res")
  system.terminate()
}

이 예제는 CSV 파일을 읽어서 각 라인을 파싱하고, 18세 이상인 사람들만 필터링한 후, 결과를 새 파일에 쓰는 과정을 보여줘. 실제 데이터 처리 파이프라인을 구축할 때 이런 방식으로 접근할 수 있어!

Akka Streams는 메모리 사용량을 효율적으로 관리하면서 대용량 데이터를 처리할 수 있어. 특히 파일 I/O, 네트워크 통신 같은 작업에서 빛을 발하지!

고급 기능: 그래프 DSL

단순한 선형 파이프라인 외에도, Akka Streams는 복잡한 그래프 구조를 구성할 수 있는 'Graph DSL'을 제공해:

import akka.stream.scaladsl.GraphDSL
import akka.stream.ClosedShape

val graph = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder =>
  import GraphDSL.Implicits._
  
  // 컴포넌트 생성
  val source = Source(1 to 10)
  val broadcast = builder.add(Broadcast[Int](2)) // 1개 입력, 2개 출력
  val zip = builder.add(Zip[Int, Int]()) // 2개 입력, 1개 출력(튜플)
  val sink = Sink.foreach[(Int, Int)](println)
  
  // 컴포넌트 연결
  source ~> broadcast
  broadcast.out(0) ~> zip.in0
  broadcast.out(1).map(_ * 10) ~> zip.in1
  zip.out ~> sink
  
  ClosedShape
})

graph.run()

이 예제는 숫자 스트림을 두 갈래로 나누고, 한 쪽은 그대로 두고 다른 쪽은 10을 곱한 후, 두 스트림을 다시 합쳐서 튜플로 만드는 과정을 보여줘.

실행 결과는 다음과 같아:

(1,10)
(2,20)
(3,30)
(4,40)
(5,50)
(6,60)
(7,70)
(8,80)
(9,90)
(10,100)

이런 그래프 DSL을 사용하면 분기, 병합, 우선순위 처리 등 복잡한 데이터 흐름을 구현할 수 있어!

7. 분산 시스템 구축: Akka 클러스터 🌐

지금까지는 단일 JVM 내에서 Akka를 사용하는 방법을 알아봤어. 하지만 Akka의 진정한 강점은 여러 서버에 걸쳐 분산 시스템을 쉽게 구축할 수 있다는 점이야. 이제 Akka Cluster에 대해 알아보자!

Akka Cluster 소개

Akka Cluster는 여러 노드(서버)에 걸쳐 액터 시스템을 분산시키고, 이들이 하나의 클러스터로 동작하게 해주는 기능이야. 주요 특징은 다음과 같아:

  1. 탄력적 멤버십: 노드가 동적으로 클러스터에 참여하거나 떠날 수 있어.
  2. 장애 감지: 노드 장애를 자동으로 감지하고 대응할 수 있어.
  3. 위치 투명성: 액터가 어느 노드에 있든 동일한 방식으로 통신할 수 있어.
  4. 분산 게시/구독: 클러스터 전체에 메시지를 브로드캐스트할 수 있어.
  5. 클러스터 샤딩: 데이터나 작업을 여러 노드에 분산시킬 수 있어.
Node 1 A1 A2 A3 A4 A5 Node 2 B1 B2 B3 B4 B5 Node 3 C1 C2 C3 C4 C5 Akka Cluster: 분산 액터 시스템

Akka Cluster를 사용하면 단일 서버의 한계를 넘어서 수평적으로 확장 가능한 시스템을 구축할 수 있어. 트래픽이 증가하면 간단히 노드를 추가하기만 하면 돼!

Akka Cluster 설정

Akka Cluster를 사용하기 위해서는 먼저 의존성을 추가해야 해:

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-cluster-typed" % akkaVersion,
  "com.typesafe.akka" %% "akka-cluster-sharding-typed" % akkaVersion
)

그리고 application.conf 파일에 클러스터 설정을 추가해:

akka {
  actor {
    provider = "cluster"
  }
  remote {
    artery {
      canonical {
        hostname = "127.0.0.1"
        port = 2551
      }
    }
  }
  cluster {
    seed-nodes = [
      "akka://ClusterSystem@127.0.0.1:2551",
      "akka://ClusterSystem@127.0.0.1:2552"
    ]
    downing-provider-class = "akka.cluster.sbr.SplitBrainResolverProvider"
  }
}

이 설정에서 중요한 부분은:

  1. actor.provider = "cluster": 액터 시스템이 클러스터 모드로 동작하도록 설정.
  2. remote.artery: 노드 간 통신을 위한 네트워크 설정.
  3. cluster.seed-nodes: 클러스터 형성을 위한 초기 노드 목록.
  4. downing-provider-class: 분할 브레인(split brain) 상황을 해결하기 위한 전략.

클러스터 노드 생성

이제 클러스터 노드를 생성하는 코드를 작성해보자:

import akka.actor.typed.ActorSystem
import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors
import akka.cluster.typed.Cluster
import com.typesafe.config.ConfigFactory

object ClusterApp {
  
  object ClusterListener {
    sealed trait Command
    case class MemberEvent(event: String) extends Command
    
    def apply(): Behavior[Command] = Behaviors.setup { context =>
      val cluster = Cluster(context.system)
      
      context.log.info("Node started with address: {}", cluster.selfMember.address)
      
      Behaviors.receiveMessage {
        case MemberEvent(event) =>
          context.log.info("Cluster event: {}", event)
          Behaviors.same
      }
    }
  }
  
  def main(args: Array[String]): Unit = {
    // 커맨드 라인에서 포트 번호를 받음
    val port = if (args.isEmpty) "2551" else args(0)
    
    // 포트 번호를 설정에 오버라이드
    val config = ConfigFactory.parseString(
      s"""
         |akka.remote.artery.canonical.port = $port
       """.stripMargin
    ).withFallback(ConfigFactory.load())
    
    // 액터 시스템 생성
    val system = ActorSystem[Nothing](
      Behaviors.setup[Nothing] { context =>
        // 클러스터 리스너 액터 생성
        val listener = context.spawn(ClusterListener(), "clusterListener")
        
        // 클러스터 이벤트를 구독
        val cluster = Cluster(context.system)
        cluster.subscriptions.tell(akka.cluster.typed.Subscribe(
          listener, classOf[akka.cluster.ClusterEvent.MemberEvent]
        ))
        
        Behaviors.empty
      },
      "ClusterSystem",
      config
    )
  }
}

이 코드는:

  1. 커맨드 라인 인자로 포트 번호를 받아서 설정을 오버라이드해.
  2. ClusterListener 액터를 생성해서 클러스터 이벤트를 모니터링해.
  3. 클러스터 멤버십 이벤트를 구독해서 노드 참여/이탈 정보를 로깅해.

이 애플리케이션을 다른 포트로 여러 번 실행하면, 각 인스턴스가 클러스터의 노드로 참여하게 돼!

클러스터 샤딩(Cluster Sharding)

클러스터의 가장 강력한 기능 중 하나는 '클러스터 샤딩'이야. 이를 통해 많은 수의 액터를 여러 노드에 분산시킬 수 있어:

import akka.actor.typed.ActorSystem
import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors
import akka.cluster.sharding.typed.scaladsl.{ClusterSharding, Entity, EntityTypeKey}

object UserEntity {
  // 메시지 프로토콜
  sealed trait Command
  final case class Get(replyTo: akka.actor.typed.ActorRef[String]) extends Command
  final case class Update(value: String) extends Command
  
  // 엔티티 타입 키 (샤딩에서 엔티티 타입 식별에 사용)
  val TypeKey = EntityTypeKey[Command]("User")
  
  // 엔티티 행동 정의
  def apply(entityId: String): Behavior[Command] = {
    behavior(entityId, "")
  }
  
  private def behavior(entityId: String, value: String): Behavior[Command] = {
    Behaviors.receiveMessage {
      case Get(replyTo) =>
        replyTo ! s"User $entityId has value: $value"
        Behaviors.same
      case Update(newValue) =>
        behavior(entityId, newValue)
    }
  }
}

object ShardingExample {
  def main(args: Array[String]): Unit = {
    // 액터 시스템 생성
    val system = ActorSystem[Nothing](Behaviors.empty, "ClusterSystem")
    
    // 클러스터 샤딩 초기화
    val sharding = ClusterSharding(system)
    
    // UserEntity 타입 등록
    val userRegion = sharding.init(Entity(
      UserEntity.TypeKey,
      createBehavior = ctx => UserEntity(ctx.entityId)
    ))
    
    // 특정 사용자 엔티티에 메시지 전송
    userRegion ! akka.cluster.sharding.typed.ShardingEnvelope(
      "user-1", 
      UserEntity.Update("Hello from sharding")
    )
  }
}

클러스터 샤딩의 핵심 개념은:

  1. 엔티티(Entity): 샤딩의 기본 단위. 각 엔티티는 고유 ID로 식별돼.
  2. 샤드(Shard): 여러 엔티티를 그룹화한 단위. 샤드 단위로 노드 간 이동이 일어나.
  3. 샤드 리전(Shard Region): 각 노드에서 샤드 집합을 관리하는 액터.

클러스터 샤딩을 사용하면 수백만 개의 엔티티를 여러 노드에 분산시키면서도, 마치 로컬에 있는 것처럼 투명하게 접근할 수 있어!

분산 데이터(Distributed Data)

Akka Cluster는 분산 데이터 기능도 제공해. 이를 통해 클러스터 전체에 걸쳐 데이터를 복제하고 동기화할 수 있어:

import akka.actor.typed.ActorSystem
import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors
import akka.cluster.ddata.typed.scaladsl.{DistributedData, Replicator}
import akka.cluster.ddata.typed.scaladsl.Replicator._
import akka.cluster.ddata.{LWWMap, LWWMapKey}

object DistributedDataExample {
  
  sealed trait Command
  case class UpdateData(key: String, value: String) extends Command
  case class GetData(key: String, replyTo: akka.actor.typed.ActorRef[DataResponse]) extends Command
  case class DataResponse(value: Option[String]) extends Command
  
  def apply(): Behavior[Command] = Behaviors.setup { context =>
    // DistributedData 확장 접근
    val replicator = DistributedData(context.system).replicator
    
    // LWWMap 키 생성 (Last Write Wins Map)
    val DataKey = LWWMapKey[String, String]("example-data")
    
    Behaviors.receiveMessage {
      case UpdateData(key, value) =>
        // 데이터 업데이트 요청
        replicator ! Update(
          DataKey,
          LWWMap.empty[String, String],
          WriteLocal,
          Some(context.self.narrow[UpdateResponse[LWWMap[String, String]]])
        )(_ + (key -> value))
        
        Behaviors.same
        
      case GetData(key, replyTo) =>
        // 데이터 조회 요청
        replicator ! Get(
          DataKey,
          ReadLocal,
          Some(context.self.narrow[GetResponse[LWWMap[String, String]]])
        )
        
        // 응답 처리를 위한 어댑터 생성
        context.messageAdapter[GetResponse[LWWMap[String, String]]] {
          case r @ GetSuccess(DataKey, _) =>
            val value = r.get(DataKey).get(key)
            DataResponse(value)
          case _ =>
            DataResponse(None)
        }
        
        Behaviors.same
    }
  }
}

분산 데이터는 다음과 같은 데이터 타입을 제공해:

  1. GCounter: 증가만 가능한 카운터
  2. PNCounter: 증가/감소 가능한 카운터
  3. GSet: 요소 추가만 가능한 집합
  4. ORSet: 요소 추가/제거 가능한 집합
  5. LWWMap: 키-값 맵 (충돌 시 최신 쓰기 우선)
  6. ORMap: 충돌 해결 가능한 맵

이런 분산 데이터 타입들은 CRDT(Conflict-free Replicated Data Types)라는 수학적 모델을 기반으로 하며, 네트워크 파티션 상황에서도 일관성을 유지할 수 있어!

클러스터 싱글톤(Cluster Singleton)

클러스터 전체에서 단 하나의 인스턴스만 실행되어야 하는 작업이 있을 때는 '클러스터 싱글톤'을 사용할 수 있어:

import akka.actor.typed.ActorSystem
import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors
import akka.cluster.typed.{ClusterSingleton, SingletonActor}

object ClusterSingletonExample {
  
  object SingletonActor {
    sealed trait Command
    case object DoWork extends Command
    
    def apply(): Behavior[Command] = Behaviors.setup { context =>
      context.log.info("Singleton actor started on node: {}", 
        akka.cluster.typed.Cluster(context.system).selfMember.address)
      
      Behaviors.receiveMessage {
        case DoWork =>
          context.log.info("Singleton is doing work")
          Behaviors.same
      }
    }
  }
  
  def main(args: Array[String]): Unit = {
    val system = ActorSystem[Nothing](Behaviors.empty, "ClusterSystem")
    
    // 클러스터 싱글톤 매니저 접근
    val singleton = ClusterSingleton(system)
    
    // 싱글톤 액터 등록
    val singletonManager = singleton.init(
      SingletonActor(
        SingletonActor(), 
        "global-singleton"
      )
    )
    
    // 싱글톤 액터에 메시지 전송
    singletonManager ! SingletonActor.DoWork
  }
}

클러스터 싱글톤은 다음과 같은 상황에서 유용해:

  1. 전역 설정 관리
  2. 리더 선출이 필요한 작업
  3. 중복 실행을 피해야 하는 스케줄링 작업
  4. 순차적 처리가 필요한 글로벌 작업

클러스터 싱글톤은 노드 장애 시 자동으로 다른 노드에서 재시작돼. 하지만 이 과정에서 약간의 지연이 발생할 수 있으니 주의해야 해!

이렇게 Akka Cluster를 사용하면 단일 서버의 한계를 넘어서 확장 가능하고 탄력적인 분산 시스템을 구축할 수 있어. 재능넷 같은 대규모 플랫폼도 이런 기술을 활용하면 사용자가 늘어나도 안정적으로 서비스를 제공할 수 있을 거야!

8. Akka HTTP로 웹 서비스 개발하기 🌍

지금까지 Akka의 핵심 기능들을 살펴봤어. 이제는 이런 기능들을 활용해서 실제 웹 서비스를 구축하는 방법을 알아보자! Akka HTTP는 Akka 스트림 위에 구축된 경량 HTTP 서버/클라이언트 라이브러리야.

Akka HTTP 소개

Akka HTTP는 다음과 같은 특징을 가지고 있어:

  1. 스트림 기반: Akka Streams를 기반으로 하여 백프레셔를 지원해.
  2. 완전한 HTTP 스택: 저수준 서버/클라이언트 API부터 고수준 라우팅 DSL까지 제공해.
  3. 유연한 마샬링: JSON, XML 등 다양한 형식의 데이터 변환을 지원해.
  4. WebSocket 지원: 양방향 통신을 위한 WebSocket 프로토콜을 지원해.
  5. 타입 안전성: Scala의 타입 시스템을 활용한 안전한 API를 제공해.

먼저 의존성을 추가해보자:

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-http" % "10.5.0",
  "com.typesafe.akka" %% "akka-http-spray-json" % "10.5.0"
)

첫 번째 HTTP 서버

간단한 HTTP 서버를 만들어보자:

import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn

object WebServer {
  def main(args: Array[String]): Unit = {
    // 액터 시스템 생성
    implicit val system: ActorSystem[Nothing] = ActorSystem(
      Behaviors.empty, 
      "WebServer"
    )
    
    // 필요한 실행 컨텍스트
    implicit val executionContext: ExecutionContextExecutor = system.executionContext
    
    // 라우트 정의
    val route = 
      path("hello") {
        get {
          complete(HttpEntity(
            ContentTypes.`text/html(UTF-8)`,
            "

Hello from Akka HTTP!

" )) } } ~ path("ping") { get { complete("pong") } } // 서버 바인딩 val bindingFuture = Http().newServerAt("localhost", 8080).bind(route) println(s"Server online at http://localhost:8080/\nPress RETURN to stop...") StdIn.readLine() // 콘솔에서 엔터 입력 대기 // 서버 종료 bindingFuture .flatMap(_.unbind()) .onComplete(_ => system.terminate()) } }

이 코드는 두 개의 엔드포인트를 가진 간단한 웹 서버를 생성해:

  1. GET /hello: HTML 응답을 반환
  2. GET /ping: "pong" 텍스트 응답을 반환

Akka HTTP의 라우팅 DSL은 매우 직관적이고 조합 가능해. 다양한 경로와 HTTP 메서드를 조합해서 복잡한 API도 쉽게 구현할 수 있지!

JSON 처리

실제 웹 서비스에서는 JSON 형식으로 데이터를 주고받는 경우가 많아. Akka HTTP에서는 spray-json을 사용해서 JSON 처리를 할 수 있어:

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.DefaultJsonProtocol

// 도메인 모델
final case class User(name: String, age: Int, email: String)
final case class Users(users: List[User])

// JSON 마샬링 지원
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val userFormat = jsonFormat3(User)
  implicit val usersFormat = jsonFormat1(Users)
}

object UserServer extends JsonSupport {
  
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem(Behaviors.empty, "UserServer")
    implicit val executionContext = system.executionContext
    
    // 사용자 데이터
    var users = List(
      User("Alice", 25, "alice@example.com"),
      User("Bob", 30, "bob@example.com")
    )
    
    // 라우트 정의
    val route = 
      pathPrefix("users") {
        concat(
          // 모든 사용자 조회
          get {
            complete(Users(users))
          },
          // 새 사용자 추가
          post {
            entity(as[User]) { user =>
              users = users :+ user
              complete(StatusCodes.Created, "User added")
            }
          },
          // ID로 사용자 조회
          path(IntNumber) { id =>
            get {
              if (id >= 0 && id < users.length) {
                complete(users(id))
              } else {
                complete(StatusCodes.NotFound, "User not found")
              }
            }
          }
        )
      }
    
    val bindingFuture = Http().newServerAt("localhost", 8080).bind(route)
    
    println(s"Server online at http://localhost:8080/")
    
    // 종료 처리
    sys.addShutdownHook {
      bindingFuture
        .flatMap(_.unbind())
        .onComplete(_ => system.terminate())
    }
  }
}

이 예제에서는:

  1. User와 Users 케이스 클래스를 정의해서 도메인 모델을 표현해.
  2. JsonSupport 트레이트를 통해 JSON 변환 규칙을 정의해.
  3. GET /users 엔드포인트로 모든 사용자를 조회할 수 있어.
  4. POST /users 엔드포인트로 새 사용자를 추가할 수 있어.
  5. GET /users/{id} 엔드포인트로 특정 사용자를 조회할 수 있어.

Akka HTTP의 entity(as[T]) 디렉티브는 자동으로 요청 본문을 지정된 타입으로 변환해줘. 마찬가지로 응답에서도 케이스 클래스가 자동으로 JSON으로 변환돼!

액터와 HTTP 서버 통합

Akka HTTP의 진정한 강점은 액터 시스템과의 통합이야. 웹 요청을 액터에게 전달하고, 액터의 응답을 클라이언트에게 반환하는 패턴을 구현해보자:

import akka.actor.typed.{ActorRef, ActorSystem, Behavior}
import akka.actor.typed.scaladsl.{Behaviors, AskPattern}
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.util.Timeout
import spray.json.DefaultJsonProtocol

import scala.concurrent.duration._
import scala.concurrent.Future

// 도메인 모델 및 프로토콜
final case class Task(id: String, description: String, completed: Boolean)

object TaskManager {
  // 액터 프로토콜
  sealed trait Command
  final case class GetTasks(replyTo: ActorRef[Tasks]) extends Command
  final case class GetTask(id: String, replyTo: ActorRef[Option[Task]]) extends Command
  final case class CreateTask(task: Task, replyTo: ActorRef[TaskCreated]) extends Command
  final case class TaskCreated(id: String) extends Command
  
  final case class Tasks(tasks: List[Task])
  
  // 액터 행동 정의
  def apply(): Behavior[Command] = behavior(List.empty)
  
  private def behavior(tasks: List[Task]): Behavior[Command] = {
    Behaviors.receiveMessage {
      case GetTasks(replyTo) =>
        replyTo ! Tasks(tasks)
        Behaviors.same
        
      case GetTask(id, replyTo) =>
        replyTo ! tasks.find(_.id == id)
        Behaviors.same
        
      case CreateTask(task, replyTo) =>
        replyTo ! TaskCreated(task.id)
        behavior(tasks :+ task)
    }
  }
}

// JSON 지원
trait TaskJsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val taskFormat = jsonFormat3(Task)
  implicit val tasksFormat = jsonFormat1(TaskManager.Tasks)
  implicit val taskCreatedFormat = jsonFormat1(TaskManager.TaskCreated)
}

object TaskService extends TaskJsonSupport {
  
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem(Behaviors.empty, "TaskService")
    implicit val executionContext = system.executionContext
    
    // 타임아웃 설정
    implicit val timeout: Timeout = 3.seconds
    
    // TaskManager 액터 생성
    val taskManager = system.systemActorOf(TaskManager(), "taskManager")
    
    // 라우트 정의
    val route = 
      pathPrefix("tasks") {
        concat(
          // 모든 태스크 조회
          get {
            val tasks: Future[TaskManager.Tasks] = 
              AskPattern.ask(taskManager, TaskManager.GetTasks)(timeout, system.scheduler)
            
            onSuccess(tasks) { result =>
              complete(result)
            }
          },
          // 새 태스크 생성
          post {
            entity(as[Task]) { task =>
              val created: Future[TaskManager.TaskCreated] = 
                AskPattern.ask(taskManager, ref => TaskManager.CreateTask(task, ref))(timeout, system.scheduler)
              
              onSuccess(created) { result =>
                complete(StatusCodes.Created, result)
              }
            }
          },
          // ID로 태스크 조회
          path(Segment) { id =>
            get {
              val taskOption: Future[Option[Task]] = 
                AskPattern.ask(taskManager, ref => TaskManager.GetTask(id, ref))(timeout, system.scheduler)
              
              onSuccess(taskOption) {
                case Some(task) => complete(task)
                case None => complete(StatusCodes.NotFound, s"Task $id not found")
              }
            }
          }
        )
      }
    
    // 서버 시작
    val bindingFuture = Http().newServerAt("localhost", 8080).bind(route)
    
    println(s"Server online at http://localhost:8080/")
    
    // 종료 처리
    sys.addShutdownHook {
      bindingFuture
        .flatMap(_.unbind())
        .onComplete(_ => system.terminate())
    }
  }
}

이 예제에서는:

  1. TaskManager 액터가 태스크 데이터를 관리해.
  2. HTTP 라우트에서는 AskPattern을 사용해 액터에게 요청을 보내고 응답을 기다려.
  3. 액터의 응답을 HTTP 응답으로 변환해서 클라이언트에게 반환해.

이런 방식으로 HTTP 계층과 비즈니스 로직을 분리할 수 있어. 액터는 상태 관리와 비즈니스 로직을 담당하고, HTTP 계층은 요청 라우팅과 직렬화만 처리하지!

WebSocket 지원

Akka HTTP는 WebSocket도 지원해. 실시간 양방향 통신이 필요한 애플리케이션에서 유용하게 사용할 수 있어:

import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.http.scaladsl.server.Directives._
import akka.stream.scaladsl.{Flow, Sink, Source}

object WebSocketServer {
  
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem(Behaviors.empty, "WebSocketServer")
    implicit val executionContext = system.executionContext
    
    // WebSocket 핸들러 정의
    val websocketRoute = 
      path("ws-echo") {
        get {
          handleWebSocketMessages(echoService)
        }
      } ~
      path("ws-chat") {
        get {
          handleWebSocketMessages(chatFlow)
        }
      }
    
    // 정적 파일 서빙 (HTML, JS 등)
    val staticRoute = 
      pathEndOrSingleSlash {
        getFromResource("web/index.html")
      } ~
      path("static" / Remaining) { file =>
        getFromResource(s"web/$file")
      }
    
    // 전체 라우트 조합
    val route = websocketRoute ~ staticRoute
    
    // 서버 시작
    val bindingFuture = Http().newServerAt("localhost", 8080).bind(route)
    
    println(s"Server online at http://localhost:8080/")
    
    // 종료 처리
    sys.addShutdownHook {
      bindingFuture
        .flatMap(_.unbind())
        .onComplete(_ => system.terminate())
    }
  }
  
  // 에코 서비스: 받은 메시지를 그대로 반환
  def echoService: Flow[Message, Message, Any] = 
    Flow[Message].map {
      case TextMessage.Strict(text) => TextMessage(s"ECHO: $text")
      case _ => TextMessage("Unsupported message type")
    }
  
  // 채팅 서비스: 모든 연결된 클라이언트에게 메시지 브로드캐스트
  def chatFlow: Flow[Message, Message, Any] = {
    // 브로드캐스트 허브
    val (sink, source) = 
      akka.stream.scaladsl.MergeHub.source[String](perProducerBufferSize = 16)
        .toMat(akka.stream.scaladsl.BroadcastHub.sink(bufferSize = 256))(akka.stream.scaladsl.Keep.both)
        .run()
    
    // 메시지 변환 및 연결
    Flow[Message]
      .collect {
        case TextMessage.Strict(text) => text
      }
      .via(Flow[String].map(msg => s"[${java.time.LocalTime.now()}] $msg"))
      .to(sink)
      .merge(source)
      .map(TextMessage(_))
  }
}

이 예제는 두 가지 WebSocket 엔드포인트를 제공해:

  1. /ws-echo: 클라이언트가 보낸 메시지를 그대로 반환하는 에코 서비스
  2. /ws-chat: 모든 연결된 클라이언트에게 메시지를 브로드캐스트하는 채팅 서비스

WebSocket 구현에서는 Akka Streams의 Flow를 사용해. 이를 통해 메시지 변환, 필터링, 라우팅 등 복잡한 처리도 간결하게 구현할 수 있어!

HTTP 클라이언트

Akka HTTP는 서버뿐만 아니라 클라이언트 기능도 제공해. 다른 서비스의 API를 호출할 때 유용하게 사용할 수 있어:

import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.DefaultJsonProtocol

import scala.concurrent.Future
import scala.util.{Failure, Success}

// 응답 모델
final case class GithubRepo(name: String, description: Option[String], stars: Int)
final case class GithubUser(login: String, name: Option[String], repos: List[GithubRepo])

// JSON 포맷 정의
trait GithubJsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val repoFormat = jsonFormat3(GithubRepo)
  implicit val userFormat = jsonFormat3(GithubUser)
}

object HttpClientExample extends GithubJsonSupport {
  
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem(Behaviors.empty, "HttpClient")
    implicit val executionContext = system.dispatcher
    
    // GitHub API 호출
    val username = "akka"
    val userFuture = fetchGithubUser(username)
    
    userFuture.onComplete {
      case Success(user) =>
        println(s"User: ${user.login} (${user.name.getOrElse("No name")})")
        println(s"Repositories: ${user.repos.size}")
        user.repos.sortBy(-_.stars).take(5).foreach { repo =>
          println(s"- ${repo.name}: ${repo.stars} stars - ${repo.description.getOrElse("No description")}")
        }
        system.terminate()
        
      case Failure(ex) =>
        println(s"Error: ${ex.getMessage}")
        system.terminate()
    }
  }
  
  def fetchGithubUser(username: String)(implicit system: ActorSystem[_]): Future[GithubUser] = {
    implicit val executionContext = system.executionContext
    
    // 사용자 정보 요청
    val userRequest = HttpRequest(
      method = HttpMethods.GET,
      uri = s"https://api.github.com/users/$username",
      headers = List(headers.Accept(MediaTypes.`application/json`))
    )
    
    // 레포지토리 정보 요청
    val reposRequest = HttpRequest(
      method = HttpMethods.GET,
      uri = s"https://api.github.com/users/$username/repos?sort=updated",
      headers = List(headers.Accept(MediaTypes.`application/json`))
    )
    
    // HTTP 클라이언트
    val http = Http(system)
    
    // 사용자 정보 가져오기
    for {
      userResponse <- http.singleRequest(userRequest)
      userData <- Unmarshal(userResponse.entity).to[Map[String, spray.json.JsValue]]
      
      reposResponse <- http.singleRequest(reposRequest)
      reposData <- Unmarshal(reposResponse.entity).to[List[Map[String, spray.json.JsValue]]]
      
      // 데이터 변환
      repos = reposData.map { repo =>
        GithubRepo(
          name = repo("name").convertTo[String],
          description = repo.get("description").map(_.convertTo[String]),
          stars = repo("stargazers_count").convertTo[Int]
        )
      }
    } yield {
      GithubUser(
        login = userData("login").convertTo[String],
        name = userData.get("name").map(_.convertTo[String]),
        repos = repos
      )
    }
  }
}

이 예제는 GitHub API를 호출해서 특정 사용자의 정보와 레포지토리 목록을 가져와. Akka HTTP 클라이언트는 비동기적으로 동작하며, Akka Streams와 통합되어 있어서 대용량 데이터도 효율적으로 처리할 수 있어!

Akka HTTP를 사용하면 서버와 클라이언트 모두 동일한 추상화와 API로 구현할 수 있어. 이는 마이크로서비스 아키텍처에서 특히 유용하지!

이렇게 Akka HTTP를 사용하면 확장 가능하고 유연한 웹 서비스를 쉽게 구축할 수 있어. 재능넷 같은 플랫폼의 API 서버도 이런 기술로 구현하면 높은 성능과 안정성을 확보할 수 있을 거야!

9. 실전 프로젝트: 채팅 애플리케이션 만들기 💬

지금까지 배운 내용을 종합해서 실전 프로젝트를 만들어보자! Akka의 다양한 기능을 활용한 실시간 채팅 애플리케이션을 구현할 거야.

프로젝트 개요

우리가 만들 채팅 애플리케이션의 주요 기능은 다음과 같아:

  1. 사용자 등록 및 로그인
  2. 채팅방 생성 및 참여
  3. 실시간 메시지 교환
  4. 사용자 상태 표시(온라인/오프라인)
  5. 메시지 히스토리 저장 및 조회

이 애플리케이션은 다음과 같은 Akka 컴포넌트를 활용할 거야:

  1. Akka Actors: 사용자와 채팅방 관리
  2. Akka Cluster: 여러 서버에 걸친 확장성 제공
  3. Akka HTTP: REST API 및 WebSocket 연결 처리
  4. Akka Persistence: 메시지 히스토리 저장
  5. Akka Streams: 메시지 처리 파이프라인 구성
클라이언트 Akka HTTP WebSocket 액터 시스템 UserActor RoomActor ChatActor Supervisor Akka Persistence 이벤트 저장소 채팅 애플리케이션 아키텍처 Akka 기반 실시간 분산 채팅 시스템

도메인 모델 정의

먼저 채팅 애플리케이션의 도메인 모델을 정의해보자:

// 도메인 모델
final case class User(id: String, name: String)
final case class ChatRoom(id: String, name: String, ownerId: String)
final case class Message(id: String, roomId: String, userId: String, content: String, timestamp: Long)

// 이벤트 모델 (영속성을 위한)
sealed trait ChatEvent
final case class UserJoinedEvent(userId: String, roomId: String, timestamp: Long) extends ChatEvent
final case class UserLeftEvent(userId: String, roomId: String, timestamp: Long) extends ChatEvent
final case class MessagePostedEvent(message: Message) extends ChatEvent

// 명령 모델 (액터 메시지)
sealed trait UserCommand
final case class JoinRoom(roomId: String, replyTo: ActorRef[StatusResponse]) extends UserCommand
final case class LeaveRoom(roomId: String, replyTo: ActorRef[StatusResponse]) extends UserCommand
final case class PostMessage(roomId: String, content: String, replyTo: ActorRef[StatusResponse]) extends UserCommand
final case class GetUserRooms(replyTo: ActorRef[RoomsResponse]) extends UserCommand

sealed trait RoomCommand
final case class JoinRoomRequest(userId: String, replyTo: ActorRef[StatusResponse]) extends RoomCommand
final case class LeaveRoomRequest(userId: String, replyTo: ActorRef[StatusResponse]) extends RoomCommand
final case class PostMessageRequest(message: Message, replyTo: ActorRef[StatusResponse]) extends RoomCommand
final case class GetRoomUsers(replyTo: ActorRef[UsersResponse]) extends RoomCommand
final case class GetRoomMessages(limit: Int, replyTo: ActorRef[MessagesResponse]) extends RoomCommand

// 응답 모델
final case class StatusResponse(success: Boolean, message: String)
final case class RoomsResponse(rooms: List[ChatRoom])
final case class UsersResponse(users: List[User])
final case class MessagesResponse(messages: List[Message])

사용자 액터 구현

사용자를 관리하는 UserActor를 구현해보자:

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.{Behaviors, ActorContext}
import akka.cluster.sharding.typed.scaladsl.EntityTypeKey

object UserActor {
  // 엔티티 타입 키 (클러스터 샤딩용)
  val TypeKey = EntityTypeKey[UserCommand]("User")
  
  // 팩토리 메서드
  def apply(userId: String): Behavior[UserCommand] = Behaviors.setup { context =>
    // 사용자 정보 로드 (실제로는 DB에서 로드할 수 있음)
    val user = User(userId, s"User-$userId")
    
    // 초기 상태로 시작
    active(context, user, Set.empty)
  }
  
  // 활성 상태의 행동
  private def active(
    context: ActorContext[UserCommand], 
    user: User,
    joinedRooms: Set[String]
  ): Behavior[UserCommand] = {
    Behaviors.receiveMessage {
      case JoinRoom(roomId, replyTo) =>
        context.log.info("User {} joining room {}", user.id, roomId)
        
        // 채팅방 액터 찾기 (클러스터 샤딩 사용)
        val roomActorRef = getRoomActorRef(context, roomId)
        
        // 채팅방에 참여 요청
        roomActorRef ! JoinRoomRequest(user.id, context.messageAdapter[StatusResponse] { response =>
          if (response.success) {
            replyTo ! response
            // 내부 상태 업데이트를 위한 자기 자신에게 메시지 전송
            InternalJoinRoomSuccess(roomId)
          } else {
            replyTo ! response
            InternalJoinRoomFailure()
          }
        })
        
        Behaviors.same
        
      case InternalJoinRoomSuccess(roomId) =>
        // 참여한 채팅방 목록 업데이트
        active(context, user, joinedRooms + roomId)
        
      case InternalJoinRoomFailure() =>
        // 상태 변경 없음
        Behaviors.same
        
      case LeaveRoom(roomId, replyTo) =>
        if (!joinedRooms.contains(roomId)) {
          replyTo ! StatusResponse(false, s"Not in room $roomId")
          Behaviors.same
        } else {
          context.log.info("User {} leaving room {}", user.id, roomId)
          
          val roomActorRef = getRoomActorRef(context, roomId)
          roomActorRef ! LeaveRoomRequest(user.id, context.messageAdapter[StatusResponse] { response =>
            if (response.success) {
              replyTo ! response
              InternalLeaveRoomSuccess(roomId)
            } else {
              replyTo ! response
              InternalLeaveRoomFailure()
            }
          })
          
          Behaviors.same
        }
        
      case InternalLeaveRoomSuccess(roomId) =>
        // 채팅방 목록에서 제거
        active(context, user, joinedRooms - roomId)
        
      case InternalLeaveRoomFailure() =>
        Behaviors.same
        
      case PostMessage(roomId, content, replyTo) =>
        if (!joinedRooms.contains(roomId)) {
          replyTo ! StatusResponse(false, s"Not in room $roomId")
          Behaviors.same
        } else {
          context.log.info("User {} posting message to room {}", user.id, roomId)
          
          val message = Message(
            id = java.util.UUID.randomUUID().toString,
            roomId = roomId,
            userId = user.id,
            content = content,
            timestamp = System.currentTimeMillis()
          )
          
          val roomActorRef = getRoomActorRef(context, roomId)
          roomActorRef ! PostMessageRequest(message, replyTo)
          
          Behaviors.same
        }
        
      case GetUserRooms(replyTo) =>
        // 참여 중인 채팅방 목록 조회 (실제로는 채팅방 정보를 가져와야 함)
        val rooms = joinedRooms.toList.map { roomId =>
          ChatRoom(roomId, s"Room-$roomId", "unknown")
        }
        
        replyTo ! RoomsResponse(rooms)
        Behaviors.same
    }
  }
  
  // 내부 메시지 (상태 업데이트용)
  private sealed trait InternalCommand extends UserCommand
  private case class InternalJoinRoomSuccess(roomId: String) extends InternalCommand
  private case class InternalJoinRoomFailure() extends InternalCommand
  private case class InternalLeaveRoomSuccess(roomId: String) extends InternalCommand
  private case class InternalLeaveRoomFailure() extends InternalCommand
  
  // 채팅방 액터 참조 가져오기 (클러스터 샤딩 사용)
  private def getRoomActorRef(context: ActorContext[_], roomId: String): ActorRef[RoomCommand] = {
    val sharding = akka.cluster.sharding.typed.scaladsl.ClusterSharding(context.system)
    sharding.entityRefFor(RoomActor.TypeKey, roomId)
  }
}

채팅방 액터 구현

채팅방을 관리하는 RoomActor를 구현해보자:

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.{Behaviors, ActorContext}
import akka.cluster.sharding.typed.scaladsl.EntityTypeKey
import akka.persistence.typed.PersistenceId
import akka.persistence.typed.scaladsl.{EventSourcedBehavior, Effect}

object RoomActor {
  // 엔티티 타입 키 (클러스터 샤딩용)
  val TypeKey = EntityTypeKey[RoomCommand]("Room")
  
  // 상태 모델
  final case class State(
    room: ChatRoom,
    users: Set[String] = Set.empty,
    messages: List[Message] = List.empty
  )
  
  // 팩토리 메서드
  def apply(roomId: String): Behavior[RoomCommand] = {
    Behaviors.setup { context =>
      // 채팅방 정보 로드 (실제로는 DB에서 로드할 수 있음)
      val room = ChatRoom(roomId, s"Room-$roomId", "system")
      
      // 이벤트 소스드 액터로 구현
      EventSourcedBehavior[RoomCommand, ChatEvent, State](
        persistenceId = PersistenceId.ofUniqueId(s"room-$roomId"),
        emptyState = State(room),
        commandHandler = commandHandler(context),
        eventHandler = eventHandler
      )
    }
  }
  
  // 명령 핸들러
  private def commandHandler(context: ActorContext[RoomCommand]): (State, RoomCommand) => Effect[ChatEvent, State] = {
    (state, command) => command match {
      case JoinRoomRequest(userId, replyTo) =>
        if (state.users.contains(userId)) {
          replyTo ! StatusResponse(true, s"Already in room ${state.room.id}")
          Effect.none
        } else {
          context.log.info("User {} joined room {}", userId, state.room.id)
          
          // 이벤트 저장 및 상태 업데이트
          val event = UserJoinedEvent(userId, state.room.id, System.currentTimeMillis())
          
          Effect
            .persist(event)
            .thenRun { _ =>
              // 모든 사용자에게 참여 알림 (실제로는 WebSocket 등으로 전송)
              broadcastUserJoined(context, state, userId)
              
              replyTo ! StatusResponse(true, s"Joined room ${state.room.id}")
            }
        }
        
      case LeaveRoomRequest(userId, replyTo) =>
        if (!state.users.contains(userId)) {
          replyTo ! StatusResponse(false, s"Not in room ${state.room.id}")
          Effect.none
        } else {
          context.log.info("User {} left room {}", userId, state.room.id)
          
          val event = UserLeftEvent(userId, state.room.id, System.currentTimeMillis())
          
          Effect
            .persist(event)
            .thenRun { _ =>
              // 모든 사용자에게 퇴장 알림
              broadcastUserLeft(context, state, userId)
              
              replyTo ! StatusResponse(true, s"Left room ${state.room.id}")
            }
        }
        
      case PostMessageRequest(message, replyTo) =>
        if (!state.users.contains(message.userId)) {
          replyTo ! StatusResponse(false, s"Not in room ${state.room.id}")
          Effect.none
        } else {
          context.log.info("Message posted to room {}: {}", state.room.id, message.content)
          
          val event = MessagePostedEvent(message)
          
          Effect
            .persist(event)
            .thenRun { _ =>
              // 모든 사용자에게 메시지 브로드캐스트
              broadcastMessage(context, state, message)
              
              replyTo ! StatusResponse(true, "Message posted")
            }
        }
        
      case GetRoomUsers(replyTo) =>
        // 참여 중인 사용자 목록 조회 (실제로는 사용자 정보를 가져와야 함)
        val users = state.users.toList.map { userId =>
          User(userId, s"User-$userId")
        }
        
        replyTo ! UsersResponse(users)
        Effect.none
        
      case GetRoomMessages(limit, replyTo) =>
        // 최근 메시지 조회
        val messages = state.messages.take(limit)
        
        replyTo ! MessagesResponse(messages)
        Effect.none
    }
  }
  
  // 이벤트 핸들러
  private val eventHandler: (State, ChatEvent) => State = { (state, event) =>
    event match {
      case UserJoinedEvent(userId, _, _) =>
        state.copy(users = state.users + userId)
        
      case UserLeftEvent(userId, _, _) =>
        state.copy(users = state.users - userId)
        
      case MessagePostedEvent(message) =>
        // 새 메시지를 목록 앞에 추가 (최신순)
        state.copy(messages = message :: state.messages)
    }
  }
  
  // 사용자 참여 브로드캐스트
  private def broadcastUserJoined(context: ActorContext[_], state: State, userId: String): Unit = {
    // 실제 구현에서는 WebSocket 등을 통해 알림 전송
    context.log.info("Broadcasting: User {} joined room {}", userId, state.room.id)
  }
  
  // 사용자 퇴장 브로드캐스트
  private def broadcastUserLeft(context: ActorContext[_], state: State, userId: String): Unit = {
    context.log.info("Broadcasting: User {} left room {}", userId, state.room.id)
  }
  
  // 메시지 브로드캐스트
  private def broadcastMessage(context: ActorContext[_], state: State, message: Message): Unit = {
    context.log.info("Broadcasting message in room {}: {}", state.room.id, message.content)
  }
}

RoomActor는 Akka Persistence를 사용해서 이벤트 소싱 방식으로 구현됐어. 이를 통해 모든 채팅 이벤트가 저장되고, 필요할 때 상태를 복구할 수 있지!

HTTP 및 WebSocket 인터페이스

이제 클라이언트와 통신할 수 있는 HTTP API와 WebSocket 인터페이스를 구현해보자:

import akka.actor.typed.{ActorRef, ActorSystem}
import akka.actor.typed.scaladsl.AskPattern._
import akka.cluster.sharding.typed.scaladsl.ClusterSharding
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.stream.OverflowStrategy
import akka.stream.scaladsl.{Flow, Sink, Source}
import akka.util.Timeout
import spray.json.{DefaultJsonProtocol, JsValue, JsonFormat, RootJsonFormat}

import scala.concurrent.duration._
import scala.concurrent.Future
import scala.util.{Failure, Success}

// JSON 직렬화 지원
trait ChatJsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val userFormat: RootJsonFormat[User] = jsonFormat2(User)
  implicit val chatRoomFormat: RootJsonFormat[ChatRoom] = jsonFormat3(ChatRoom)
  implicit val messageFormat: RootJsonFormat[Message] = jsonFormat5(Message)
  implicit val statusResponseFormat: RootJsonFormat[StatusResponse] = jsonFormat2(StatusResponse)
  implicit val roomsResponseFormat: RootJsonFormat[RoomsResponse] = jsonFormat1(RoomsResponse)
  implicit val usersResponseFormat: RootJsonFormat[UsersResponse] = jsonFormat1(UsersResponse)
  implicit val messagesResponseFormat: RootJsonFormat[MessagesResponse] = jsonFormat1(MessagesResponse)
}

// WebSocket 메시지 모델
sealed trait WebSocketMessage
case class ChatMessage(roomId: String, userId: String, content: String) extends WebSocketMessage
case class JoinRoomMessage(roomId: String) extends WebSocketMessage
case class LeaveRoomMessage(roomId: String) extends WebSocketMessage
case class RoomUsersMessage(roomId: String, users: List[User]) extends WebSocketMessage
case class RoomHistoryMessage(roomId: String, messages: List[Message]) extends WebSocketMessage

object ChatServer extends ChatJsonSupport {
  // WebSocket 메시지 JSON 포맷
  implicit val chatMessageFormat: RootJsonFormat[ChatMessage] = jsonFormat3(ChatMessage)
  implicit val joinRoomMessageFormat: RootJsonFormat[JoinRoomMessage] = jsonFormat1(JoinRoomMessage)
  implicit val leaveRoomMessageFormat: RootJsonFormat[LeaveRoomMessage] = jsonFormat1(LeaveRoomMessage)
  implicit val roomUsersMessageFormat: RootJsonFormat[RoomUsersMessage] = jsonFormat2(RoomUsersMessage)
  implicit val roomHistoryMessageFormat: RootJsonFormat[RoomHistoryMessage] = jsonFormat2(RoomHistoryMessage)
  
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem(
      Behaviors.empty[Nothing], 
      "ChatSystem"
    )
    implicit val executionContext = system.executionContext
    implicit val timeout: Timeout = 3.seconds
    
    // 클러스터 샤딩 초기화
    val sharding = ClusterSharding(system)
    
    // UserActor 등록
    sharding.init(Entity(
      UserActor.TypeKey,
      createBehavior = ctx => UserActor(ctx.entityId)
    ))
    
    // RoomActor 등록
    sharding.init(Entity(
      RoomActor.TypeKey,
      createBehavior = ctx => RoomActor(ctx.entityId)
    ))
    
    // 사용자 세션 관리 (실제 구현에서는 인증 추가 필요)
    val sessions = new ConcurrentHashMap[String, ActorRef[WebSocketMessage]]()
    
    // HTTP 라우트 정의
    val route = 
      pathPrefix("api") {
        // 사용자 API
        pathPrefix("users" / Segment) { userId =>
          val userRef = sharding.entityRefFor(UserActor.TypeKey, userId)
          
          concat(
            // 사용자 채팅방 목록 조회
            path("rooms") {
              get {
                val futureRooms = userRef.ask(GetUserRooms)
                onComplete(futureRooms) {
                  case Success(RoomsResponse(rooms)) => complete(rooms)
                  case Failure(ex) => complete(StatusCodes.InternalServerError, ex.getMessage)
                }
              }
            },
            
            // 채팅방 참여
            path("join" / Segment) { roomId =>
              post {
                val futureStatus = userRef.ask(ref => JoinRoom(roomId, ref))
                onComplete(futureStatus) {
                  case Success(status) => complete(status)
                  case Failure(ex) => complete(StatusCodes.InternalServerError, ex.getMessage)
                }
              }
            },
            
            // 채팅방 퇴장
            path("leave" / Segment) { roomId =>
              post {
                val futureStatus = userRef.ask(ref => LeaveRoom(roomId, ref))
                onComplete(futureStatus) {
                  case Success(status) => complete(status)
                  case Failure(ex) => complete(StatusCodes.InternalServerError, ex.getMessage)
                }
              }
            },
            
            // 메시지 전송
            path("message") {
              post {
                entity(as[ChatMessage]) { chatMessage =>
                  val futureStatus = userRef.ask(ref => 
                    PostMessage(chatMessage.roomId, chatMessage.content, ref)
                  )
                  onComplete(futureStatus) {
                    case Success(status) => complete(status)
                    case Failure(ex) => complete(StatusCodes.InternalServerError, ex.getMessage)
                  }
                }
              }
            }
          )
        },
        
        // 채팅방 API
        pathPrefix("rooms" / Segment) { roomId =>
          val roomRef = sharding.entityRefFor(RoomActor.TypeKey, roomId)
          
          concat(
            // 채팅방 사용자 목록 조회
            path("users") {
              get {
                val futureUsers = roomRef.ask(GetRoomUsers)
                onComplete(futureUsers) {
                  case Success(UsersResponse(users)) => complete(users)
                  case Failure(ex) => complete(StatusCodes.InternalServerError, ex.getMessage)
                }
              }
            },
            
            // 채팅방 메시지 히스토리 조회
            path("messages") {
              get {
                parameter("limit".as[Int].withDefault(50)) { limit =>
                  val futureMessages = roomRef.ask(ref => GetRoomMessages(limit, ref))
                  onComplete(futureMessages) {
                    case Success(MessagesResponse(messages)) => complete(messages)
                    case Failure(ex) => complete(StatusCodes.InternalServerError, ex.getMessage)
                  }
                }
              }
            }
          )
        }
      } ~
      // WebSocket 연결
      path("ws" / Segment) { userId =>
        get {
          handleWebSocketMessages(chatWebSocketFlow(userId, sharding))
        }
      } ~
      // 정적 파일 서빙
      pathEndOrSingleSlash {
        getFromResource("web/index.html")
      } ~
      path("static" / Remaining) { file =>
        getFromResource(s"web/$file")
      }
    
    // 서버 시작
    val bindingFuture = Http().newServerAt("localhost", 8080).bind(route)
    
    println(s"Server online at http://localhost:8080/")
    
    // 종료 처리
    sys.addShutdownHook {
      bindingFuture
        .flatMap(_.unbind())
        .onComplete(_ => system.terminate())
    }
  }
  
  // WebSocket 흐름 처리
  private def chatWebSocketFlow(
    userId: String, 
    sharding: ClusterSharding
  )(implicit system: ActorSystem[_], timeout: Timeout): Flow[Message, Message, Any] = {
    // 사용자 액터 참조
    val userRef = sharding.entityRefFor(UserActor.TypeKey, userId)
    
    // 메시지 스트림 소스 생성
    val (actorRef, publisher) = Source
      .actorRef[WebSocketMessage](
        completionMatcher = PartialFunction.empty,
        failureMatcher = PartialFunction.empty,
        bufferSize = 100,
        overflowStrategy = OverflowStrategy.dropHead
      )
      .toMat(Sink.asPublisher(fanout = false))(Keep.both)
      .run()
    
    // 세션 등록
    sessions.put(userId, actorRef)
    
    // 클라이언트 메시지 처리
    val incomingFlow = Flow[Message]
      .collect {
        case TextMessage.Strict(text) =>
          // JSON 파싱 및 메시지 처리
          val json = spray.json.JsonParser(text)
          
          if (json.asJsObject.fields.contains("content")) {
            // 채팅 메시지
            val chatMessage = json.convertTo[ChatMessage]
            userRef ! PostMessage(chatMessage.roomId, chatMessage.content, system.ignoreRef)
          } else if (json.asJsObject.fields.contains("roomId")) {
            if (json.asJsObject.fields.contains("join")) {
              // 채팅방 참여
              val joinMessage = json.convertTo[JoinRoomMessage]
              userRef ! JoinRoom(joinMessage.roomId, system.ignoreRef)
            } else if (json.asJsObject.fields.contains("leave")) {
              // 채팅방 퇴장
              val leaveMessage = json.convertTo[LeaveRoomMessage]
              userRef ! LeaveRoom(leaveMessage.roomId, system.ignoreRef)
            }
          }
      }
      .to(Sink.ignore)
    
    // 클라이언트로 메시지 전송
    val outgoingFlow = Source.fromPublisher(publisher)
      .map {
        case msg: ChatMessage =>
          TextMessage(spray.json.enrichAny(msg).toJson.toString)
        case msg: RoomUsersMessage =>
          TextMessage(spray.json.enrichAny(msg).toJson.toString)
        case msg: RoomHistoryMessage =>
          TextMessage(spray.json.enrichAny(msg).toJson.toString)
        case _ =>
          TextMessage("Unknown message type")
      }
    
    // 연결 종료 처리
    val flow = Flow.fromSinkAndSource(incomingFlow, outgoingFlow)
      .watchTermination() { (_, futureTermination) =>
        futureTermination.onComplete { _ =>
          // 세션 제거
          sessions.remove(userId)
          system.log.info("WebSocket connection for user {} closed", userId)
        }
      }
    
    flow
  }
}

이 코드는 다음과 같은 기능을 제공해:

  1. REST API: 사용자와 채팅방 관리를 위한 HTTP 엔드포인트
  2. WebSocket 인터페이스: 실시간 메시지 교환을 위한 양방향 통신
  3. 클러스터 샤딩: 사용자와 채팅방 액터를 여러 노드에 분산

이 애플리케이션은 확장성이 뛰어나! 사용자가 늘어나면 간단히 노드를 추가하기만 하면 돼. 각 사용자와 채팅방은 클러스터 전체에 분산되어 관리돼.

프론트엔드 구현

마지막으로 간단한 프론트엔드 코드를 작성해보자:

// index.html



  
  
  Akka Chat
  


  
// chat.js let userId = ''; let currentRoomId = ''; let socket = null; // DOM 요소 const loginContainer = document.getElementById('login-container'); const chatContainer = document.getElementById('chat-container'); const usernameInput = document.getElementById('username'); const loginBtn = document.getElementById('login-btn'); const currentUserElement = document.getElementById('current-user'); const roomListElement = document.getElementById('room-list'); const userListElement = document.getElementById('user-list'); const messagesElement = document.getElementById('messages'); const messageInput = document.getElementById('message-input'); const sendBtn = document.getElementById('send-btn'); const currentRoomElement = document.getElementById('current-room'); const newRoomNameInput = document.getElementById('new-room-name'); const createRoomBtn = document.getElementById('create-room-btn'); // 로그인 처리 loginBtn.addEventListener('click', () => { const username = usernameInput.value.trim(); if (username) { userId = username; currentUserElement.textContent = username; // 로그인 화면 숨기고 채팅 화면 표시 loginContainer.style.display = 'none'; chatContainer.style.display = 'flex'; // 채팅방 목록 로드 loadRooms(); // WebSocket 연결 connectWebSocket(); } }); // WebSocket 연결 function connectWebSocket() { socket = new WebSocket(`ws://${window.location.host}/ws/${userId}`); socket.onopen = () => { console.log('WebSocket connected'); }; socket.onmessage = (event) => { const data = JSON.parse(event.data); if (data.content) { // 채팅 메시지 if (data.roomId === currentRoomId) { addMessage(data); } } else if (data.users) { // 사용자 목록 업데이트 if (data.roomId === currentRoomId) { updateUserList(data.users); } } else if (data.messages) { // 메시지 히스토리 if (data.roomId === currentRoomId) { updateMessageHistory(data.messages); } } }; socket.onclose = () => { console.log('WebSocket disconnected'); // 재연결 로직 추가 가능 }; } // 채팅방 목록 로드 function loadRooms() { fetch(`/api/users/${userId}/rooms`) .then(response => response.json()) .then(rooms => { roomListElement.innerHTML = ''; rooms.forEach(room => { const li = document.createElement('li'); li.textContent = room.name; li.dataset.roomId = room.id; li.addEventListener('click', () => selectRoom(room.id, room.name)); roomListElement.appendChild(li); }); }) .catch(error => console.error('Error loading rooms:', error)); } // 채팅방 선택 function selectRoom(roomId, roomName) { currentRoomId = roomId; currentRoomElement.textContent = roomName; // 이전 채팅방 메시지 비우기 messagesElement.innerHTML = ''; // 채팅방 사용자 목록 로드 loadRoomUsers(roomId); // 채팅방 메시지 히스토리 로드 loadRoomMessages(roomId); } // 채팅방 사용자 목록 로드 function loadRoomUsers(roomId) { fetch(`/api/rooms/${roomId}/users`) .then(response => response.json()) .then(users => { updateUserList(users); }) .catch(error => console.error('Error loading users:', error)); } // 사용자 목록 업데이트 function updateUserList(users) { userListElement.innerHTML = ''; users.forEach(user => { const li = document.createElement('li'); li.textContent = user.name; li.dataset.userId = user.id; userListElement.appendChild(li); }); } // 채팅방 메시지 히스토리 로드 function loadRoomMessages(roomId) { fetch(`/api/rooms/${roomId}/messages`) .then(response => response.json()) .then(messages => { updateMessageHistory(messages); }) .catch(error => console.error('Error loading messages:', error)); } // 메시지 히스토리 업데이트 function updateMessageHistory(messages) { messagesElement.innerHTML = ''; messages.forEach(message => { addMessage(message); }); // 스크롤을 최신 메시지로 이동 messagesElement.scrollTop = messagesElement.scrollHeight; } // 메시지 추가 function addMessage(message) { const messageElement = document.createElement('div'); messageElement.className = 'message'; if (message.userId === userId) { messageElement.classList.add('own-message'); } const nameElement = document.createElement('div'); nameElement.className = 'message-name'; nameElement.textContent = message.userId; const contentElement = document.createElement('div'); contentElement.className = 'message-content'; contentElement.textContent = message.content; const timeElement = document.createElement('div'); timeElement.className = 'message-time'; timeElement.textContent = new Date(message.timestamp).toLocaleTimeString(); messageElement.appendChild(nameElement); messageElement.appendChild(contentElement); messageElement.appendChild(timeElement); messagesElement.appendChild(messageElement); // 스크롤을 최신 메시지로 이동 messagesElement.scrollTop = messagesElement.scrollHeight; } // 메시지 전송 sendBtn.addEventListener('click', sendMessage); messageInput.addEventListener('keypress', (event) => { if (event.key === 'Enter') { sendMessage(); } }); function sendMessage() { const content = messageInput.value.trim(); if (content && currentRoomId) { const message = { roomId: currentRoomId, userId: userId, content: content }; // WebSocket으로 메시지 전송 socket.send(JSON.stringify(message)); // 입력 필드 비우기 messageInput.value = ''; } } // 새 채팅방 생성 createRoomBtn.addEventListener('click', () => { const roomName = newRoomNameInput.value.trim(); if (roomName) { // 실제 구현에서는 서버에 채팅방 생성 요청 alert('Room creation not implemented in this demo'); newRoomNameInput.value = ''; } });

이 프론트엔드 코드는 다음과 같은 기능을 제공해:

  1. 사용자 로그인
  2. 채팅방 목록 표시 및 선택
  3. 채팅방 내 사용자 목록 표시
  4. 메시지 전송 및 수신
  5. 메시지 히스토리 표시

이렇게 Akka의 다양한 기능을 활용해서 확장 가능한 실시간 채팅 애플리케이션을 구현할 수 있어! 이 프로젝트는 재능넷 같은 플랫폼에서 사용자 간 실시간 소통 기능을 구현할 때 참고할 수 있는 좋은 예시가 될 거야.

10. 성능 최적화와 모니터링 📊

Akka 기반 애플리케이션을 운영할 때는 성능 최적화와 모니터링이 매우 중요해. 이 섹션에서는 Akka 애플리케이션의 성능을 최적화하고 모니터링하는 방법을 알아보자!

디스패처(Dispatcher) 최적화

Akka에서 디스패처는 액터에게 실행 시간을 할당하는 스레드 풀이야. 적절한 디스패처 설정은 성능에 큰 영향을 미쳐:

akka {
  actor {
    # 기본 디스패처
    default-dispatcher {
      type = Dispatcher
      executor = "fork-join-executor"
      
      fork-join-executor {
        parallelism-min = 8
        parallelism-factor = 3.0
        parallelism-max = 64
      }
      
      throughput = 10
    }
    
    # I/O 작업을 위한 디스패처
    io-dispatcher {
      type = Dispatcher
      executor = "thread-pool-executor"
      
      thread-pool-executor {
        fixed-pool-size = 16
      }
      
      throughput = 1
    }
    
    # CPU 집약적 작업을 위한 디스패처
    cpu-dispatcher {
      type = Dispatcher
      executor = "fork-join-executor"
      
      fork-join-executor {
        parallelism-min = 4
        parallelism-factor = 2.0
        parallelism-max = 32
      }
      
      throughput = 5
    }
  }
}

디스패처 설정의 주요 매개변수는 다음과 같아:

  1. parallelism-min: 최소 스레드 수
  2. parallelism-factor: CPU 코어 수에 대한 스레드 수 비율
  3. parallelism-max: 최대 스레드 수
  4. throughput: 한 액터가 다른 액터에게 양보하기 전에 처리할 메시지 수

액터에 특정 디스패처를 지정하는 방법은 다음과 같아:

// 스프링 설정에서 디스패처 지정
val workerActor = context.spawn(
  WorkerActor(),
  "worker",
  DispatcherSelector.fromConfig("akka.actor.cpu-dispatcher")
)

// 또는 액터 내부에서 지정
def apply(): Behavior[Command] = {
  Behaviors.setup { context =>
    // 이 액터는 I/O 디스패처에서 실행됨
    context.self.tell(SwitchDispatcher("akka.actor.io-dispatcher"))
    
    Behaviors.receiveMessage {
      case SwitchDispatcher(dispatcherId) =>
        context.setDispatcherFromConfig(dispatcherId)
        Behaviors.same
      // 다른 메시지 처리...
    }
  }
}

작업 특성에 맞는 디스패처를 사용하는 것이 중요해! I/O 작업은 thread-pool-executor가, CPU 집약적 작업은 fork-join-executor가 적합해.

라우터(Router) 활용

부하가 큰 작업을 여러 액터에 분산시키기 위해 라우터를 사용할 수 있어:

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.{Behaviors, Routers}

object WorkerPool {
  sealed trait Command
  case class Process(data: String, replyTo: ActorRef[Result]) extends Command
  case class Result(data: String)
  
  def apply(): Behavior[Command] = {
    Behaviors.setup { context =>
      // 풀 라우터 생성 (8개의 워커)
      val pool = Routers.pool(8)(
        // 각 워커의 행동 정의
        Behaviors.receiveMessage[Command] {
          case Process(data, replyTo) =>
            // 작업 처리
            val result = processData(data)
            replyTo ! Result(result)
            Behaviors.same
        }
      )
      
      // 라우터 생성
      val router = context.spawn(pool, "worker-pool")
      
      // 메시지를 라우터에 전달
      Behaviors.receiveMessage {
        case msg: Process =>
          router ! msg
          Behaviors.same
      }
    }
  }
  
  private def processData(data: String): String = {
    // 실제 데이터 처리 로직
    s"Processed: $data"
  }
}

Akka는 다양한 라우팅 전략을 제공해:

  1. RoundRobinPool: 순차적으로 메시지를 분배
  2. RandomPool: 무작위로 메시지를 분배
  3. SmallestMailboxPool: 가장 적은 메시지를 가진 액터에게 분배
  4. BroadcastPool: 모든 액터에게 메시지를 전달
  5. ConsistentHashingPool: 메시지의 해시값에 따라 분배

메모리 사용 최적화

Akka 애플리케이션의 메모리 사용을 최적화하는 방법은 다음과 같아:

  1. 액터 수 관리: 너무 많은 액터를 생성하지 않도록 주의해. 필요할 때만 생성하고, 사용이 끝나면 중지해.
  2. 메시지 크기 제한: 큰 메시지는 메모리 사용량을 증가시키고 GC 부하를 높여. 가능하면 참조나 ID만 전달해.
  3. 메일박스 크기 제한: 무한정 메시지가 쌓이지 않도록 메일박스 크기를 제한해.
  4. 불변 객체 사용: 가능한 한 불변(immutable) 객체를 사용해 메모리 사용을 최적화해.

메일박스 크기를 제한하는 설정 예시:

akka {
  actor {
    default-mailbox {
      mailbox-type = "akka.dispatch.BoundedMailbox"
      mailbox-capacity = 1000
      mailbox-push-timeout-time = 10s
    }
  }
}

Akka 메트릭스 활성화

Akka는 내부 메트릭스를 수집하고 모니터링 시스템에 노출할 수 있는 기능을 제공해. 먼저 의존성을 추가해:

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor-typed" % akkaVersion,
  "com.typesafe.akka" %% "akka-cluster-typed" % akkaVersion,
  "io.kamon" %% "kamon-bundle" % "2.2.3",
  "io.kamon" %% "kamon-prometheus" % "2.2.3"
)

그리고 설정 파일에 메트릭스 활성화 설정을 추가해:

akka {
  actor {
    provider = "cluster"
  }
  
  # 메트릭스 활성화
  metrics {
    enabled = on
    
    # 어떤 메트릭스를 수집할지 설정
    filter {
      router-dispatcher {
        includes = ["akka.actor.default-dispatcher"]
      }
      actor {
        includes = ["user/*"]
        excludes = ["system/*"]
      }
    }
  }
}

# Kamon 설정
kamon {
  metric {
    tick-interval = 10 seconds
  }
  
  prometheus {
    start-embedded-http-server = yes
    embedded-server {
      hostname = 0.0.0.0
      port = 9095
    }
  }
}

애플리케이션 시작 시 Kamon을 초기화해:

import kamon.Kamon

object Main {
  def main(args: Array[String]): Unit = {
    // Kamon 시작
    Kamon.init()
    
    // Akka 시스템 시작
    val system = ActorSystem(...)
    
    // 종료 시 Kamon 종료
    sys.addShutdownHook {
      Kamon.stop()
      system.terminate()
    }
  }
}

이제 Prometheus나 Grafana 같은 도구를 사용해 메트릭스를 시각화할 수 있어!

Akka 애플리케이션 액터 시스템 클러스터 스트림 HTTP Kamon 메트릭스 수집 트레이싱 컨텍스트 전파 리포팅 Prometheus Grafana Akka 모니터링 아키텍처

주요 모니터링 지표

Akka 애플리케이션에서 모니터링해야 할 주요 지표는 다음과 같아:

  1. 액터 메일박스 크기: 메일박스에 쌓인 메시지 수. 증가하면 처리 지연 발생 가능.
  2. 액터 처리 시간: 메시지 처리에 걸리는 시간. 병목 지점 식별에 유용.
  3. 디스패처 사용률: 스레드 풀 사용 현황. 과도한 사용은 성능 저하 원인.
  4. 메모리 사용량: 힙 메모리 사용량과 GC 활동. 메모리 누수 감지에 중요.
  5. 클러스터 지표: 노드 수, 샤드 분포, 노드 간 통신량 등.
  6. 오류 발생률: 예외 발생 횟수와 유형. 시스템 안정성 평가에 중요.

Grafana 대시보드 예시:

{
  "annotations": {
    "list": []
  },
  "editable": true,
  "gnetId": null,
  "graphTooltip": 0,
  "id": 1,
  "links": [],
  "panels": [
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "Prometheus",
      "fill": 1,
      "fillGradient": 0,
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 0
      },
      "hiddenSeries": false,
      "id": 2,
      "legend": {
        "avg": false,
        "current": false,
        "max": false,
        "min": false,
        "show": true,
        "total": false,
        "values": false
      },
      "lines": true,
      "linewidth": 1,
      "nullPointMode": "null",
      "options": {
        "dataLinks": []
      },
      "percentage": false,
      "pointradius": 2,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "expr": "akka_actor_mailbox_size{actor_path=~\"user/.*\"}",
          "legendFormat": "{{actor_path}}",
          "refId": "A"
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeRegions": [],
      "timeShift": null,
      "title": "액터 메일박스 크기",
      "tooltip": {
        "shared": true,
        "sort": 0,
        "value_type": "individual"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    }
  ],
  "refresh": "5s",
  "schemaVersion": 22,
  "style": "dark",
  "tags": [],
  "templating": {
    "list": []
  },
  "time": {
    "from": "now-15m",
    "to": "now"
  },
  "timepicker": {},
  "timezone": "",
  "title": "Akka 모니터링",
  "uid": "akka",
  "version": 1
}

성능 테스트

Akka 애플리케이션의 성능을 테스트하기 위한 도구와 방법은 다음과 같아:

  1. Gatling: Scala로 작성된 부하 테스트 도구. Akka HTTP 애플리케이션 테스트에 적합.
  2. JMH (Java Microbenchmark Harness): 세부적인 성능 벤치마킹에 유용.
  3. Akka TestKit: 액터의 동작과 성능을 테스트하기 위한 도구.

Gatling을 사용한 부하 테스트 예시:

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._

class ChatSimulation extends Simulation {
  
  val httpProtocol = http
    .baseUrl("http://localhost:8080")
    .acceptHeader("application/json")
    .contentTypeHeader("application/json")
  
  val scn = scenario("Chat Room Scenario")
    // 사용자 로그인
    .exec(http("Login")
      .post("/api/login")
      .body(StringBody("""{"username":"user${userId}","password":"password"}"""))
      .check(jsonPath("$.token").saveAs("authToken"))
    )
    .pause(1)
    
    // 채팅방 목록 조회
    .exec(http("Get Rooms")
      .get("/api/users/${userId}/rooms")
      .header("Authorization", "Bearer ${authToken}")
      .check(jsonPath("$[0].id").saveAs("roomId"))
    )
    .pause(1)
    
    // 채팅방 참여
    .exec(http("Join Room")
      .post("/api/users/${userId}/join/${roomId}")
      .header("Authorization", "Bearer ${authToken}")
    )
    .pause(1)
    
    // 메시지 전송 (10회 반복)
    .repeat(10) {
      exec(http("Send Message")
        .post("/api/users/${userId}/message")
        .header("Authorization", "Bearer ${authToken}")
        .body(StringBody("""{"roomId":"${roomId}","content":"Hello from user${userId} - ${iteration}"}"""))
      )
      .pause(2)
    }
    
    // 채팅방 퇴장
    .exec(http("Leave Room")
      .post("/api/users/${userId}/leave/${roomId}")
      .header("Authorization", "Bearer ${authToken}")
    )
  
  // 시뮬레이션 설정
  setUp(
    scn.inject(
      // 1초마다 1명씩 사용자 증가, 최대 100명
      rampUsers(100).during(100.seconds)
    ).protocols(httpProtocol)
  )
}

성능 테스트는 실제 운영 환경과 유사한 조건에서 수행하는 것이 중요해! 특히 클러스터 환경에서는 여러 노드에 걸친 테스트가 필요해.

운영 환경에서의 모범 사례

Akka 애플리케이션을 운영 환경에서 안정적으로 실행하기 위한 모범 사례는 다음과 같아:

  1. 적절한 JVM 설정: GC 튜닝, 힙 크기 설정 등 JVM 매개변수 최적화.
  2. 로깅 전략: 효과적인 로깅 설정으로 문제 진단 용이성 확보.
  3. 회로 차단기(Circuit Breaker) 패턴: 외부 서비스 호출 시 장애 격리.
  4. 백오프 전략: 오류 발생 시 점진적으로 재시도 간격 증가.
  5. 분할 두뇌(Split Brain) 해결: 네트워크 파티션 상황에서의 전략 수립.
  6. 정기적인 백업: 특히 Akka Persistence 사용 시 이벤트 저장소 백업.

회로 차단기 패턴 구현 예시:

import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.Behaviors
import akka.pattern.{CircuitBreaker, CircuitBreakerOpenException}

import scala.concurrent.duration._
import scala.util.{Failure, Success}

object ExternalServiceActor {
  sealed trait Command
  case class CallService(data: String, replyTo: ActorRef[Response]) extends Command
  case class Response(result: String)
  
  def apply(): Behavior[Command] = {
    Behaviors.setup { context =>
      implicit val ec = context.executionContext
      
      // 회로 차단기 생성
      val breaker = CircuitBreaker(
        context.system.scheduler,
        maxFailures = 5,           // 5번 실패하면 회로 열림
        callTimeout = 2.seconds,   // 호출 타임아웃
        resetTimeout = 30.seconds  

10. 성능 최적화와 모니터링 📊 (계속)

      // 회로 차단기 생성 (이전 코드에서 계속)
      val breaker = CircuitBreaker(
        context.system.scheduler,
        maxFailures = 5,           // 5번 실패하면 회로 열림
        callTimeout = 2.seconds,   // 호출 타임아웃
        resetTimeout = 30.seconds  // 30초 후 반열림 상태로 전환
      )
      
      Behaviors.receiveMessage {
        case CallService(data, replyTo) =>
          context.log.info("Calling external service with data: {}", data)
          
          // 회로 차단기를 통한 외부 서비스 호출
          breaker.withCircuitBreaker(callExternalService(data))
            .onComplete {
              case Success(result) =>
                replyTo ! Response(result)
              case Failure(ex: CircuitBreakerOpenException) =>
                context.log.warning("Circuit breaker open, not calling service")
                replyTo ! Response("Service unavailable - circuit open")
              case Failure(ex) =>
                context.log.error("Service call failed: {}", ex.getMessage)
                replyTo ! Response("Service call failed: " + ex.getMessage)
            }
          
          Behaviors.same
      }
    }
  }
  
  // 외부 서비스 호출 시뮬레이션
  private def callExternalService(data: String)(implicit ec: ExecutionContext): Future[String] = {
    Future {
      // 실제로는 HTTP 요청 등을 수행
      if (Random.nextDouble() < 0.3) { // 30% 확률로 실패
        throw new RuntimeException("External service error")
      }
      Thread.sleep(500) // 서비스 호출 지연 시뮬레이션
      s"Response for: $data"
    }
  }
}

백오프 감독 전략 예시:

import akka.actor.typed.{ActorRef, Behavior, SupervisorStrategy}
import akka.actor.typed.scaladsl.Behaviors

import scala.concurrent.duration._

object DatabaseActor {
  sealed trait Command
  case class Query(sql: String, replyTo: ActorRef[Result]) extends Command
  case class Result(data: String)
  
  def apply(): Behavior[Command] = {
    // 백오프 감독 전략 적용
    val supervised = Behaviors.supervise(
      database()
    ).onFailure[Exception](
      SupervisorStrategy.restartWithBackoff(
        minBackoff = 1.second,
        maxBackoff = 1.minute,
        randomFactor = 0.2
      ).withMaxRestarts(10)
    )
    
    supervised
  }
  
  private def database(): Behavior[Command] = {
    Behaviors.receiveMessage {
      case Query(sql, replyTo) =>
        try {
          // 데이터베이스 쿼리 실행 (예시)
          val result = executeQuery(sql)
          replyTo ! Result(result)
        } catch {
          case ex: Exception =>
            // 예외 발생 시 상위로 전파 (감독 전략에 의해 처리됨)
            throw ex
        }
        
        Behaviors.same
    }
  }
  
  private def executeQuery(sql: String): String = {
    // 실제 데이터베이스 쿼리 실행 코드
    // 예시 구현
    if (sql.contains("error")) {
      throw new RuntimeException("Database error")
    }
    s"Result for: $sql"
  }
}

로깅 및 추적

효과적인 로깅은 문제 진단에 필수적이야. Akka는 SLF4J를 통한 로깅을 지원해:

// logback.xml 설정 예시

  
    
      %date{ISO8601} %-5level %logger{36} [%X{akkaSource}] - %msg%n
    
  
  
  
    logs/application.log
    
      logs/application.%d{yyyy-MM-dd}.log
      30
    
    
      %date{ISO8601} %-5level %logger{36} [%X{akkaSource}] - %msg%n
    
  
  
  
  
  
  
  
  
  
    
    
  

액터에서 로깅 사용 예시:

def apply(): Behavior[Command] = {
  Behaviors.setup { context =>
    // 로거 접근
    val log = context.log
    
    Behaviors.receiveMessage {
      case ImportantMessage(data) =>
        // 다양한 로그 레벨 사용
        log.info("Received important message: {}", data)
        
        try {
          processData(data)
        } catch {
          case ex: Exception =>
            // 예외 로깅
            log.error("Error processing data: {}", ex.getMessage, ex)
        }
        
        Behaviors.same
        
      case DebugMessage(data) =>
        // 디버그 로깅 (조건부)
        if (log.isDebugEnabled) {
          log.debug("Debug data: {}", data)
        }
        
        Behaviors.same
    }
  }
}

분산 추적을 위해 Kamon과 Jaeger를 활용할 수도 있어:

libraryDependencies ++= Seq(
  "io.kamon" %% "kamon-bundle" % "2.2.3",
  "io.kamon" %% "kamon-jaeger" % "2.2.3"
)

// kamon.conf
kamon {
  trace {
    sampler = "always"
    join-remote-parents-with-same-span-id = true
  }
  
  jaeger {
    host = "jaeger"
    port = 14268
    protocol = "http"
  }
}

클러스터 모니터링

Akka 클러스터를 모니터링하기 위한 특별한 도구와 설정도 있어:

akka {
  cluster {
    # 클러스터 메트릭스 활성화
    metrics {
      enabled = on
      
      # 메트릭스 수집 간격
      collector {
        sample-interval = 3s
        moving-average-half-life = 10s
      }
    }
    
    # 분할 두뇌 해결자 설정
    downing-provider-class = "akka.cluster.sbr.SplitBrainResolverProvider"
    split-brain-resolver {
      active-strategy = keep-majority
      stable-after = 20s
    }
  }
}

클러스터 상태를 시각화하는 Lightbend Console이나 오픈소스 대안인 Akka Cluster Visualizer 같은 도구도 활용할 수 있어.

클러스터 환경에서는 샤드 재조정, 노드 참여/이탈, 분할 두뇌 해결 등의 이벤트를 모니터링하는 것이 중요해. 이를 통해 클러스터의 안정성을 유지할 수 있어!

성능 튜닝 체크리스트

Akka 애플리케이션의 성능을 최적화하기 위한 체크리스트를 정리해보자:

  1. 액터 세분화: 너무 많은 액터를 만들지 않았는지, 또는 너무 적은 액터로 병렬성을 제한하지 않았는지 확인.
  2. 메시지 크기: 큰 객체를 메시지로 전달하지 않고, 가능하면 참조나 ID만 전달하는지 확인.
  3. 불변성: 메시지와 상태가 불변(immutable) 객체로 구현되었는지 확인.
  4. 디스패처 설정: 작업 특성에 맞는 디스패처를 사용하고 있는지 확인.
  5. 라우터 활용: 부하가 큰 작업을 여러 액터에 분산시키기 위해 라우터를 활용하는지 확인.
  6. 메일박스 크기: 메일박스 크기를 모니터링하고 필요시 제한하는지 확인.
  7. 블로킹 작업 처리: 블로킹 작업은 전용 디스패처에서 처리하는지 확인.
  8. Future 처리: Future 완료 콜백에서 무거운 작업을 수행하지 않는지 확인.
  9. 메모리 누수: 액터 참조를 제대로 관리하고 사용하지 않는 액터를 중지하는지 확인.
  10. JVM 설정: GC 설정, 힙 크기 등 JVM 매개변수가 최적화되었는지 확인.

성능 최적화는 측정 가능한 데이터를 기반으로 해야 해! 추측이 아닌 프로파일링과 벤치마킹을 통해 실제 병목 지점을 찾아 개선하는 것이 중요해.

결론: Akka와 Scala로 미래를 준비하세요! 🚀

지금까지 Scala와 Akka를 이용한 동시성 프로그래밍의 다양한 측면을 살펴봤어. 이제 배운 내용을 정리하고, 앞으로의 방향에 대해 생각해보자!

배운 내용 요약

  1. Scala와 Akka의 조합: 함수형 프로그래밍과 액터 모델의 강력한 시너지
  2. 액터 모델: 메시지 기반 통신으로 동시성 문제를 단순화하는 패러다임
  3. Akka의 핵심 기능: 액터, 스트림, 클러스터, HTTP 등 다양한 모듈
  4. 분산 시스템: 클러스터 샤딩, 분산 데이터 등을 통한 확장성 있는 시스템 구축
  5. 실시간 애플리케이션: 채팅 시스템 같은 실시간 서비스 구현 방법
  6. 성능 최적화: 디스패처, 라우터, 메모리 관리 등 성능 향상 기법
  7. 모니터링: 메트릭스 수집과 시각화를 통한 시스템 관찰

Akka의 미래

Akka는 계속 발전하고 있어. 최근에는 다음과 같은 트렌드가 주목받고 있지:

  1. 클라우드 네이티브: Kubernetes와의 통합, 컨테이너화된 배포
  2. 서버리스: FaaS(Function as a Service) 패러다임과의 통합
  3. 이벤트 소싱과 CQRS: 상태 관리와 쿼리 최적화를 위한 패턴
  4. 디지털 트윈: IoT 장치의 가상 표현을 액터로 모델링
  5. ML/AI 통합: 머신러닝 모델과 액터 시스템의 결합

다음 단계

Akka와 Scala를 더 깊이 배우고 싶다면 다음과 같은 자료를 참고해봐:

  1. 공식 문서: Akka 공식 문서는 가장 정확하고 최신 정보를 제공해.
  2. 책: "Akka in Action", "Reactive Design Patterns" 같은 책들이 도움이 될 거야.
  3. 온라인 과정: Lightbend Academy, Coursera의 "Reactive Architecture" 과정 등이 있어.
  4. 오픈소스 프로젝트: GitHub에서 Akka를 사용한 실제 프로젝트를 살펴보는 것도 좋은 방법이야.
  5. 커뮤니티: Akka Gitter 채널, Stack Overflow 등에서 다른 개발자들과 소통해봐.

마치며

Scala와 Akka는 현대적인 동시성 프로그래밍을 위한 강력한 도구야. 멀티코어 CPU, 분산 시스템, 클라우드 환경이 일반화된 오늘날, 이런 기술은 더욱 중요해지고 있어.

특히 재능넷 같은 대규모 플랫폼을 구축할 때, 확장성과 탄력성을 갖춘 시스템이 필수적이지. Akka는 이런 요구사항을 충족시키는 데 이상적인 프레임워크야.

이 글이 Scala와 Akka의 세계로 첫발을 내딛는 데 도움이 되었기를 바라! 행운을 빌어! 🚀

댓글 작성

이 글에 대한 여러분의 생각을 들려주세요

댓글 0
댓글을 불러오는 중입니다.

아직 댓글이 없습니다.