akak中还有一个比较重要的概念,那就是Router(路由)。路由的概念,相信大家都不陌生,在akka中,它就是其他actors的一个代理,会把消息按照路由规则,分发给指定的actor。我一般喜欢把Router用作负载均衡。
其实如果不看官方的源码或不使用官方Router,我们自己实现一个router也还是很简单的,因为一共有三个重要的概念:路由、路由策略、路由对象。路由负责接收消息,按照路由策略把消息传递给路由对象。在akka中,路由和路由对象都是一个普通的actor,只不过路由策略需要我们涉及的通用些,能够支持各种路由算法就好了。不过既然官方实现了Router,就研读一下喽。
老规矩,还是从官方demo入手,分析Router的相关源码。
import akka.routing.{ ActorRefRoutee, RoundRobinRoutingLogic, Router } class Master extends Actor { var router = { val routees = Vector.fill(5) { val r = context.actorOf(Props[Worker]) context watch r ActorRefRoutee(r) } Router(RoundRobinRoutingLogic(), routees) } def receive = { case w: Work ⇒ router.route(w, sender()) case Terminated(a) ⇒ router = router.removeRoutee(a) val r = context.actorOf(Props[Worker]) context watch r router = router.addRoutee(r) } }
很简单,上面master启动的时候,通过actorOf创建了5个Worker,然后收到Work消息时,调用routee分发消息。当然了在收到worker的Terminated消息后,又重新创建了一个worker。这只是router的一个用法,我个人是不喜欢的,因为它定死了worker的个数。
/ * For each message that is sent through the router via the [[#route]] method the * [[RoutingLogic]] decides to which [[Routee]] to send the message. The [[Routee]] itself * knows how to perform the actual sending. Normally the [[RoutingLogic]] picks one of the * contained `routees`, but that is up to the implementation of the [[RoutingLogic]]. * * A `Router` is immutable and the [[RoutingLogic]] must be thread safe. */ final case class Router(val logic: RoutingLogic, val routees: immutable.IndexedSeq[Routee] = Vector.empty)
上面是Router的定义,这居然是一个case class,有两个变量:路由逻辑(RoutingLogic)、路由对象(IndexedSeq[Routee])。
/ * The interface of the routing logic that is used in a [[Router]] to select * destination routed messages. * * The implementation must be thread safe. */ trait RoutingLogic extends NoSerializationVerificationNeeded { / * Pick the destination for a given message. Normally it picks one of the * passed `routees`, but in the end it is up to the implementation to * return whatever [[Routee]] to use for sending a specific message. * * When implemented from Java it can be good to know that * `routees.apply(index)` can be used to get an element * from the `IndexedSeq`. */ def select(message: Any, routees: immutable.IndexedSeq[Routee]): Routee }
上面是RoutingLogic的定义,要不要这么简单呢?就只有一个select函数,它根据message和路由对象集合返回了一个路由目标。
/ * Abstraction of a destination for messages routed via a [[Router]]. */ trait Routee { def send(message: Any, sender: ActorRef): Unit }
路由对象是啥呢?就是一个只包含send方法的trait,也非常简单。其实吧,路由对象只要能发送消息就行了,不管他是ActorRef还是ActorSelection。
上面是Router的完整源码,一共分四部分功能:路由消息、给指定路由对象发送消息、路由对象操作、消息解包。
/ * Send the message to the destination [[Routee]] selected by the [[RoutingLogic]]. * If the message is a [[akka.routing.RouterEnvelope]] it will be unwrapped * before sent to the destinations. * Messages wrapped in a [[Broadcast]] envelope are always sent to all `routees`. */ def route(message: Any, sender: ActorRef): Unit = message match { case akka.routing.Broadcast(msg) ⇒ SeveralRoutees(routees).send(msg, sender) case msg ⇒ send(logic.select(msg, routees), message, sender) }
route方法非常简单,首先判断是不是广播消息,如果是就创建SeveralRoutees然后发送;如果不是则调用logic.select选择一个routee,然后调用send发送。先来分析SeveralRoutees
/ * [[Routee]] that sends each message to all `routees`. */ final case class SeveralRoutees(routees: immutable.IndexedSeq[Routee]) extends Routee { / * Java API */ def this(rs: java.lang.Iterable[Routee]) = this(routees = immutableSeq(rs).toVector) / * Java API */ def getRoutees(): java.util.List[Routee] = { import scala.collection.JavaConverters._ routees.asJava } override def send(message: Any, sender: ActorRef): Unit = routees.foreach(_.send(message, sender)) }
SeveralRoutees首先这是一个Routee,然后覆盖了send方法,send里面依次调用routees集合的send方法。由于在Broadcast(广播)消息传入了整个routees,所以也就是给当前路由的所有路由对象都发送了消息。怎么样,是不是非常简单呢?
既然router和routerLogic都这么简单,而且他们只接收Routee,那么跟ActorRef和ActorSelection如何关联呢?看到官方demo中的ActorRefRoutee了吗?
/ * [[Routee]] that sends the messages to an [[akka.actor.ActorRef]]. */ final case class ActorRefRoutee(ref: ActorRef) extends Routee { override def send(message: Any, sender: ActorRef): Unit = ref.tell(message, sender) }
ActorRefRoutee就是对ActorRef的封装,它覆盖send方法,调用ActorRef的tell方法把消息发送出去。就是这么简单,那ActorSelection也是这样喽?对的,就是这样。
/ * [[Routee]] that sends the messages to an [[akka.actor.ActorSelection]]. */ final case class ActorSelectionRoutee(selection: ActorSelection) extends Routee { override def send(message: Any, sender: ActorRef): Unit = selection.tell(message, sender) }
这是不是太简单了点?嗯,Router的基本用法就是这么简单啊。为了篇幅,我们简单分析几个路由策略,那就分析demo中的RoundRobinRoutingLogic吧。
/ * Uses round-robin to select a routee. For concurrent calls, * round robin is just a best effort. */ @SerialVersionUID(1L) final class RoundRobinRoutingLogic extends RoutingLogic { val next = new AtomicLong override def select(message: Any, routees: immutable.IndexedSeq[Routee]): Routee = if (routees.nonEmpty) { val size = routees.size val index = (next.getAndIncrement % size).asInstanceOf[Int] routees(if (index < 0) size + index else index) } else NoRoutee }
请注意,在RoutingLogic定义中说需要满足线程安全,所以next是一个AtomicLong,至于为啥需要线程安全,这里先略过。不过如果你就是官方demo的用法,还要啥线程安全,真是浪费。
这个RoundRobinRoutingLogic的实现逻辑也很简单,就是对AtomicLong进行依次自增,然后对routees.size取余,取出对应index的routee即可。其实就是按照顺序返回列表中的素Routee,如果到达列表末尾,则从头取值。这好像也简单了点。
akka.routing.RoundRobinRoutingLogic。轮询路由策略。具体实现参照上文分析。
akka.routing.RandomRoutingLogic。随机路由策略。就是从列表中随机选择一个Routee
akka.routing.SmallestMailboxRoutingLogic。最小邮箱路由策略。就是选择各个Routee的邮箱堆积消息最少的一个。从源码来看这个是需要查找Routee的邮箱数量的,个人不太喜欢这种实现。
akka.routing.BroadcastRoutingLogic。广播路由策略。就是把消息广播出去。
akka.routing.ScatterGatherFirstCompletedRoutingLogic。广播收集第一个完成路由策略。有点拗口,简单来说就是把消息广播出去,以第一个收到的回复作为此次路由的回复。这个不建议用,因为它对所有Routee都调用了ask。如果不关心回复,则可以使用
BroadcastRoutingLogic
。akka.routing.TailChoppingRoutingLogic。尾部断续路由策略。跟
ScatterGatherFirstCompletedRoutingLogic
差不多,只不过不是广播,而是按照一个固定间隔的时间,依次给Routee发消息,收到第一个回复后,不再广播消息,以该回复作为最终回复。akka.routing.ConsistentHashingRoutingLogic。一致性hash路由策略。就是根据消息计算对应的key,key相同的消息会发送给相同的Routee。读者可以自行研究一致性HASH的实现,简单来说就是对消息和Routee都进行hash,hash相同的作为路由关系。
对于官方demo,有一点疑问,router是不是初始化必须要有值呢?而且必须是同类型的Actor呢?完全不必要。router初始化可以为空,且不一定必须是相同的Actor,只不过官方认为,既然你都它进行路由了,最好是相同类型的actor。其实吧,个人认为,路由是对消息来说的,只要路由对象能够处理该消息就行了,不必是相同类型的。Routees如何动态添加呢?我一般把需要路由消息的Actor(比如Worker),发特定消息告诉Master(也就是router),Master收到该消息后把ActorRef添加到Router中。这在remote和cluster中非常适用。
关于Router的基本概念和源码就分析完了,但官方对Router还有其他丰富的功能,比如RoundRobinPool和RoundRobinGroup,我个人不太喜欢这种实现,还是喜欢最基本的用法。感兴趣的读者可以自行阅读相关的源码。
转载于:https://www.cnblogs.com/gabry/p/9450461.html
今天的文章 Akka源码分析-Router分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/88942.html