Page History
Code Block | ||
---|---|---|
| ||
AKKA 프레임워크를 사용한 비헤이버기반 액터모델을 코틀린이 지원하는 순수 액터모델로 변환을 시도
로컬전용 이벤트 드리븐방식의 처리기를 만 |
AKKA 전용 액터모델은 다음을 참고
의존
Code Block | ||
---|---|---|
| ||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") |
- core만 있으면 되며, reactor이용시 포함됨으로 둘중 하나만 사용
- reactor를 활용한 reactive 프로그래밍이 지원됨을 의미
구현
- AKKA 의 액터와 구분하기위해 KActor(코액터) 로 네이밍 ( K-컨텐츠아님)
- 송수신 Typed를 사용하고 비헤이버 패턴 채택
Code Block | ||
---|---|---|
| ||
package com.example.kotlinbootlabs.kactor
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
sealed class HelloKActorCommand
data class Hello(val message: String, val replyTo: kotlinx.coroutines.CompletableDeferred<HelloKActorResponse>) : HelloKActorCommand()
data class GetHelloCount(val replyTo: kotlinx.coroutines.CompletableDeferred<HelloKActorResponse>) : HelloKActorCommand()
sealed class HelloKActorResponse
data class HelloResponse(val message: String) : HelloKActorResponse()
data class HelloCountResponse(val count: Int) : HelloKActorResponse()
class HelloKActor {
private val channel = Channel<HelloKActorCommand>()
private var helloCount = 0
private val scope = CoroutineScope(Dispatchers.Default)
init {
scope.launch {
for (command in channel) {
when (command) {
is Hello -> handleHello(command)
is GetHelloCount -> handleGetHelloCount(command)
}
}
}
}
private fun handleHello(command: Hello) {
if (command.message == "Hello") {
helloCount++
command.replyTo.complete(HelloResponse("Kotlin"))
} else if (command.message == "InvalidMessage") {
throw RuntimeException("Invalid message received!")
}
}
private fun handleGetHelloCount(command: GetHelloCount) {
command.replyTo.complete(HelloCountResponse(helloCount))
}
suspend fun send(command: HelloKActorCommand) {
channel.send(command)
}
fun stop() {
scope.cancel()
}
} |