链式调用在很多框架和系统中经常存在,算不得上是我自己总结的设计模式,此处只是简单介绍在Akka中的两种实现方式。我在这边博客中简化了链式调用的场景,简化后也更符合Akka的设计哲学。
trait Chained{ def receive:Receive = Actor.emptyBehavior } trait IntReceiveChained1 extends Chained{ override def receive:Receive = super.receive orElse { case i:Int => println(s"IntReceiveChained1 receive Int $i") } } trait IntReceiveChained extends Chained{ override def receive:Receive = super.receive orElse { case i:Int => println(s"IntReceive receive Int $i") } } trait StringReceiveChained extends Chained { override def receive:Receive = super.receive orElse { case i:Int => println(s"StringReceive receive Int $i") case s:String => println(s"StringReceive receive String $s") } } class ChainedActor extends Actor with IntReceiveChained with StringReceiveChained with IntReceiveChained1 { override def receive:Receive = super.receive orElse { case any => println(s"ChainingActor receive any $any") } } object ChainingPattern1 { def main(args: Array[String]): Unit = { val system = ActorSystem("ChainingPattern1",ConfigFactory.load()) val chainingActor = system.actorOf(Props(new ChainedActor),"ChainedActor") chainingActor ! 123 chainingActor ! "test" } }
输出:
IntReceive receive Int 123 StringReceive receive String test
上面这一种实现方式跟akka没有太大关系,是用scala的trait实现的。在类中调用多个Trait中都有的方法时,首先会从最右边的Trait的方法开始执行,然后依次向左执行,形成一个调用条。这个相当于设计模式中的责任链模式的一种具体实现依赖。只不过是用orElse来实现,以保证每种类型的消息都只被处理一次。我们也可以把orElse替换掉,根据条件判断是否继续调用后续函数,这个需要我们根据业务场景来选择,我就不再展开了。
trait Chaining { self => Actor private var chainedReceives = List.empty[Receive] def registerReceive( newReceive:Receive ): Unit = { chainedReceives = newReceive :: chainedReceives } def receive:Receive = chainedReceives.reduce(_ orElse _) } trait IntReceive extends Chaining{ registerReceive{ case i:Int => println(s"IntReceive receive Int $i") } } trait StringReceive extends Chaining { registerReceive{ case s:String => println(s"StringReceive receive String $s") } } class ChainingActor extends Actor with IntReceive with StringReceive{ } object ChainingPattern2 { def main(args: Array[String]): Unit = { val system = ActorSystem("ChainingPattern2",ConfigFactory.load()) val chainingActor = system.actorOf(Props(new ChainingActor),"chainingActor") chainingActor ! 123 chainingActor ! "test" } }
输出:
IntReceive receive Int 123 StringReceive receive String test
这种实现方式是将Receive函数注册到一个列表中,通过reduce把处理函数orElse串起来。与第一种方式一样,对相同的类型也都是只匹配一次。此处只是为了简化设计模式的介绍,读者也都可以根据需求修改对chainedReceives的处理方式,比如所有函数都匹配一遍,或者根据业务条件选择性的匹配。
Akka的Chain模式并不常用,但非常有用。有了它,我们就可以自由组合对消息的处理过程了。如果某个receive需要对大量的消息进行处理,我们可以对消息进行分类,创建不同的链式函数去匹配处理,可以做到高内聚低耦合的效果。