Akka를 사용하여 계승을 계산하는 다음 스칼라 코드를 고려해보십시오. 출력을 얻는 방법을 모르겠습니다.Akka : 결과를 얻는 방법?
import scala.annotation.tailrec
import akka.actor.{Actor, ActorLogging, ActorSystem, Props}
import scala.concurrent.Await
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
case class GetResult()
class FactorialCalculator extends Actor {
def receive = {
case num: Int => sender ! (num, factor(num))
}
private def factor(num: Int) = factorTail(num, 1)
@tailrec private def factorTail(num: Int, acc: BigInt): BigInt = {
(num, acc) match {
case (0, a) => a
case (n, a) => factorTail(n - 1, n * a)
}
}
}
class FactorialCollector(factorials: List[Int]) extends Actor with ActorLogging {
var list: List[BigInt] = Nil
var size = factorials.size
for (num <- factorials) {
context.actorOf(Props(new FactorialCalculator)) ! num
}
def receive = {
case (num: Int, fac: BigInt) => {
log.info(s"factorial for $num is $fac")
list = fac :: list
size -= 1
if (size == 0) {
log.info(list.toString)
context.system.shutdown()
}
}
case GetResult => sender ! list
}
}
class Factorial(factorials: List[Int]) {
val system = ActorSystem("factorial")
val collector = system.actorOf(Props(new FactorialCollector(factorials)), "collector")
implicit val timeout = Timeout(10 seconds)
val future = collector ? GetResult
val result = Await.result(future, timeout.duration)
system.awaitTermination()
}
var x = new Factorial(List(50, 18, 32, 28, 22, 42, 55, 48))
결과는 클래스 FactorialCollector
에서 계산 된 변수 list
에 저장하지만, 빈 list
을 x.result
반환된다.
마리우스에 감사드립니다. 하지만 저는 스칼라에서 초보자이며 몇 시간을 보내서 몇 가지 문서를 읽은 후에 결과를 얻을 수 없었습니다. 당신의 대답은 내가 지금까지 읽은 것보다 덜 정확하고 슬프게도 나를 도와주지 않습니다. –
나는 약간의 진전을 이뤘고 이에 따라 나의 질문을 업데이트했다. 그러나 나는 아직 결과를 얻지 못했다. –
마지막 factorial이 actor :'context.system.shutdown()'에 의해 계산 될 때 시스템을 종료합니다. 이 행을 제거하십시오. 또한 당신은 시스템이 필요 없습니다. 와일드 결과를 기다리고 있습니다. 대신 이것은 계승 클래스의 마지막 줄에'system.shutdown()'을 넣는다. –