【问题标题】:Akka: Send a future message to an ActorAkka:向 Actor 发送未来消息
【发布时间】:2013-04-30 08:43:45
【问题描述】:

我在 Actor 中有以下代码

def receive = {
    case All() => {
        val collection: BSONCollection = db("ping")
        val future:Future[List[Ping]] = collection.find(BSONDocument()).cursor[Ping].toList()
        val zender = sender
        future onComplete {
            case Success(list) => zender ! list
            case Failure(throwable) => zender ! List()
        }
    }
}

我不喜欢必须使用 onComplete 函数将结果发送回发送者参与者的方式。我想知道是否可以将它转换成这样的:

def receive = {
    case All() => {
        val collection: BSONCollection = db("ping")
        val future:Future[List[Ping]] = collection.find(BSONDocument()).cursor[Ping].toList()
        "sender ! future" // one option
        "future.map( list => sender ! list)" //Another option. I know it's not map, but maybe another function        
    }
}

我觉得未来的链接会更好。

【问题讨论】:

  • 你的第一种方法不行吗?
  • @Alex 是的,但是管道要优雅得多。
  • 好的。但是您是说 我不喜欢我必须如何使用 onComplete 函数将结果发送回发送者演员。 而您的代码正是这样做的 - 您将结果发送回发件人演员。

标签: scala akka


【解决方案1】:

您可以为此使用管道模式。只需import akka.pattern.pipe,然后您就可以使用future pipeTo actor 将消息从future 传递给actor。

【讨论】:

    【解决方案2】:

    如果您希望在发生故障时有一个空列表,您可能希望有“recover”和“pipeTo”的链式调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-29
      • 2021-09-11
      • 2015-12-09
      • 1970-01-01
      • 2019-10-17
      • 2012-09-26
      • 1970-01-01
      • 2015-02-13
      相关资源
      最近更新 更多