Akka在回复非Actor代码时避免包装未来

Akt*_*tau 6 scala future akka

我正在与Akka 2制作一个小型缓存演员并让演员不要阻止我在期货中执行所有计算.然而问题是这个actor还需要与不在actor中的代码进行交互,因此我需要使用"ask"模式来获取值.

我的问题是,在使用ask模式时,如何避免将计算的Future包含在另一个Future中?

例如

val f = myCache ? GetOrCalc("myKey", myCalculation) // this will be a Future[Future[...]] but I would like a Future[...]

// meanwhile, inside the actor
def receive = {
    case GetOrCalc(key, calculation) =>
        if (keyNotExists) sender ! Future { calculation() } // calculation() is long-running
        else sender ! cacheMap(key)
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我可以使用Future.pipeTo函数,但我担心这不会被视为非演员代码的"响应"

Vik*_*ang 6

这是解决方案:

val f = myCache ? GetOrCalc("myKey", myCalculation)

def receive = {
    case GetOrCalc(key, calculation) =>
        if (keyNotExists) Future { calculation() } pipeTo sender
        else sender ! cacheMap(key)
}
Run Code Online (Sandbox Code Playgroud)

发送和接收,未来"> http://doc.akka.io/docs/akka/2.0.3/scala/actors.html#Ask_Send-And-Receive-Future

  • 相信巴生 (3认同)
  • 它不会关闭发件人"然后",它会关闭发件人"现在"的价值.那有意义吗? (3认同)