Aggregate multiple actor responses?

2019-07-10 16:04发布

问题:

I am trying to collect health information for my application as

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
  }
}

What I need
I need a way wherein I can collect responses from versionInfo, memoryInfo, and some other info later into 1 response and send it somewhere

and I do not want a sequential or want to block the calls, what is the best way?

回答1:

I'll make a guess you meant an ask instead of a tell because you're talking about responses, so the code should be

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

Then you can type the futures.

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

And then combine

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)
    ))
}

or via for (not sure on the syntax)

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)
}


标签: scala akka