在Akka Actors中编写多个接收函数

时间:2017-09-05 10:18:16

标签: scala akka reactive-programming composition

我有一个Akka Actor管理一些消息,比如FindQuery,它们将新消息转发给其他类型的演员。这些演员将回应新类型的消息。

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... */
  }
}

在上面的示例中,QueryAck是类型为Find的消息转发的响应消息。 UpsertNAckUpsertAck是对Upsert消息的可能回复。

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

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

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

非常感谢。

1 个答案:

答案 0 :(得分:4)

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

val manageQueries: Receive = { case ... }
val manageUpserts: Receive = { case ... }

def receive = manageQueries.orElse(manageUpserts) 

希望这有帮助