【问题标题】:Compose more than one receive function in Akka Actors在 Akka Actors 中编写多个接收函数
【发布时间】:2017-09-05 10:18:16
【问题描述】:

我有一个 Akka Actor,它管理一些消息,例如 FindQuery,它们将新消息转发给其他类型的 Actor。这些参与者将以新类型的消息进行响应。

class Actorbase extends Actor {
  override def receive = {
     /* The two message below are related to each other */
     case Find(coll, id) => // Do something
     case QueryAck(key, value, u) => // Do something
     /* The three message below are related to each other */
     case Upsert(collection, id, value) => // Do something
     case Response.UpsertNAck(key, msg, u) => // Do something
     case Response.UpsertAck(key, u) => // Do something
     /* And so on... */
  }
}

在上面的例子中,QueryAckFind类型消息的转发的响应消息。 UpsertNAckUpsertAck 是对 Upsert 消息的可能响应。

为了使代码更具可读性和可维护性,我希望将这两组cases 分组为两个专用方法,即manageQueriesmanageUpserts,得到类似于以下代码的内容。

class Actorbase extends Actor {
  override def receive = {
     manageQueries.andThen(manageUpserts)
  }
}

有可能吗?我是否需要声明多个返回 Receive 对象的方法,然后以某种方式组合它们?

非常感谢。

【问题讨论】:

    标签: scala akka reactive-programming composition


    【解决方案1】:

    Receive 只是PartialFunction[Any, Unit] 的类型别名,因此您可以在任何地方定义此类别名并使用f1 orElse f2 组合它们:

    val manageQueries: Receive = { case ... }
    val manageUpserts: Receive = { case ... }
    
    def receive = manageQueries.orElse(manageUpserts) 
    

    希望对你有帮助

    【讨论】:

    • 感谢您的回复。您认为我在问题中描述的方法还是在this SO 答案中公开的方法更好?
    • 这比我认为的另一个更好(作为项目的维护者)
    猜你喜欢
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    相关资源
    最近更新 更多