scala - Akka 在响应非 Actor 代码时避免包装 future

标签 scala akka future

我正在用 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/

相关文章:

arrays - Scala,数组总是按名称调用,对吧?

rust - 如何在 Rust future 中赋予所有权

scala - 在 Scala 中打印下 X 行

akka - 访问 Actor 邮箱的消息

java - Akka Client actor 连接到 Server actor 系统

java - Akka Http解析实体Java

scala - 如何在 Thrift/Scrooge 中声明一个返回 Option 值的方法?

scala - 重试返回 Future 的函数

scala - Spark提交期间如何解决DB2 java.io.CharConversionException

scala - 使用项目中的类的 sbt 自定义任务