我正在用 Akka 2 制作一个小型缓存 actor,为了使 actor 不会阻塞,我在 future 中执行所有计算。然而,一个问题是这个actor 还需要与不是actor 本身的代码进行交互,因此我需要使用“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)
}
理想情况下,我可以使用 Future.pipeTo 函数,但恐怕这不会被视为非 Actor 代码的“响应”
最佳答案
这是解决方案:
val f = myCache ? GetOrCalc("myKey", myCalculation)
def receive = {
case GetOrCalc(key, calculation) =>
if (keyNotExists) Future { calculation() } pipeTo sender
else sender ! cacheMap(key)
}
Send-And-Receive-Future">http://doc.akka.io/docs/akka/2.0.3/scala/actors.html#Ask_Send-And-Receive-Future
关于scala - Akka 在响应非 Actor 代码时避免包装 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12455764/