4

我遵循了本教程:http ://doc.akka.io/docs/akka/2.0/intro/getting-started-first-scala.html

基本上有一个主actor响应这两个消息:

def receive = {
    case Calculate => {
      //....
    }
    case Result(value) => {
      //....
    }
}

我们发送消息“计算”,经过几次“结果”(来自奴隶演员)我们有正确的计算

现在我在 play2 控制器的一个动作中,我正在使用这个:

val promise = (master ? Calculate)(10.seconds).mapTo[String].asPromise

不幸的是(显然)我什么也没得到,因为Calculate消息确实回复了发件人的消息。

我想以某种方式让 Akka Actor 等待......并且当计算完成时将消息发送回发送者。

但是如何?...除非我以错误的方式建模!

4

2 回答 2

4

您应该forward将消息发送给从属设备(保持相同的发件人),或者将发件人包含在发给从属设备的消息中。例如:

def receive = {
  case Calculate => slave ! CalculateWithSender(sender)

  case res @ Result(value, originalSender) =>        
    val result = resultMap(originalSender) + res   // assuming results are just added
    resultMap += (originalSender -> result) 
    if (resultsAreFinished(originalSender))    
      originalSender ! result
}

或者

def receive = {
  case Calculate => slave.forward(Calculate)

  case res @ Result(value, originalSender) => 
    val result = resultMap(originalSender) + res   // assuming results are just added 
    resultMap += (originalSender -> result) 
    if (resultsAreFinished(originalSender))    
      originalSender ! result
}

或者

def receive = {
  case Calculate => slave.tell(Calculate, sender)

  case res @ Result(value, originalSender) => 
    val result = resultMap(originalSender) + res   // assuming results are just added 
    resultMap += (originalSender -> result) 
    if (resultsAreFinished(originalSender))    
      originalSender ! result
}

我不熟悉 Play 承诺,但?( ask) 返回 Akka Future。如果.asPromise将 Akka 转换Future为 Play Promise,那么您就设置好了。

于 2012-10-05T15:46:03.490 回答
1

为每个计算启动一个新参与者。将Calculate消息转发给新的actor。新参与者存储原始发件人。当结果准备好时,结果被发送给原始发送者,并且临时 actor 死亡:

class CalculateActor extends Actor {
    var origSender : ActorRef = _
    def receive {
        case Calculate => {
            origSender = sender
            slaveActors ! doStuff
            //....
    }
    case Result(value) => {
        if(results are ready) {
            origSender ! results
            self ! PoisonPill  // I'm done, time to die
        }
    }
}

class MasterActor extends Actor {
    def receive {
        case msg @ Calculate => {
            // forward sends without changing the sender
            context.actorOf(Props(new CalculateActor)).forward(msg)
        }
    }
}
于 2012-10-05T15:50:31.040 回答