聚合多个演员回应?

时间:2015-08-18 19:39:37

标签: scala akka

我正在尝试为我的应用程序收集健康信息

class HealthMonitor extends Actor with ActorLogging {
  val statusReporter = new StatusReporter
  val versionInfo = context.actorOf(Props[VersionInfo], "versionInfo")
  val memoryInfo = context.actorOf(Props[MemoryInfo], "memoryInfo")

  def receive = LoggingReceive {
    case HealthReportRequest => log.debug("Generating Health Report")
      println("Generating Health Report")
      // todo (harit): should be concurrent calls and collect results
      versionInfo ! VersionInfoRequest
      memoryInfo ! MemoryInfoRequest
  }
}

我需要什么
我需要一种方法,我可以从versionInfomemoryInfo收集回复,然后将其他信息收集到1个回复中并将其发送到某个地方

我不想要顺序或想要阻止通话,最好的方法是什么?

1 个答案:

答案 0 :(得分:2)

我会猜测你是指一个问题,而不是一个告诉,因为你是 谈论回应,所以代码应该是

def receive = LoggingReceive {
  case HealthReportRequest => log.debug("Generating Health Report")
    println("Generating Health Report")
    versionInfo ? VersionInfoRequest
    memoryInfo ? MemoryInfoRequest
}

然后你可以输入期货。

def receive = LoggingReceive {
  case HealthReportRequest =>
    versionInfo ? VersionInfoRequest mapTo[VersionInfo]
    memoryInfo ? MemoryInfoRequest mapTo[VersionInfo]
}

然后合并

def receive = LoggingReceive {
  case HealthReportRequest =>
    val version = versionInfo ? VersionInfoRequest mapTo[VersionInfo]
    val memory = (memoryInfo ? MemoryInfoRequest mapTo[VersionInfo])
    version.flatMap(v =>
      memory.map(m =>
        fun(v, m)
    ))
}

或via for(不确定语法)

def receive = LoggingReceive {
  case HealthReportRequest =>
    val version = versionInfo ? VersionInfoRequest mapTo[VersionInfo]
    val memory = (memoryInfo ? MemoryInfoRequest mapTo[VersionInfo])
    for {
      v <- version
      m <- memory
    } yield fun(v, m)
}