本想通过了解一下Akka-actor工程中主要的类的概念,来看下Akka内部运作的机制。无奈里边的类的确太多,注释中对每个类的功能也没有足够的解释。所以还是通过debug的方式,找个入手点,看一下互相之间调用的关系。

最初的选择是看一下ActorSystem的实始化过程,但发现难度挺大,因为这个初始化工作是为以后的行为做准备,所以仅根据初始化的动作,难以了解其目的是什么。所以就试着从消息发送的过程了解起,发现这个逻辑更好理解。

下面来看一下其执行过程吧。代码如下,使用默认的配置。

object Main extends App{
val system = ActorSystem("football")
val actor = system.actorOf(Props[PrintActor])
actor ! "hello"
}

想要了解的是actor ! "hello"的执行过程。


首先,actor的类型是ActorRef,在默认的配置下,这个ActorRef的具体类型为RepointableActorRef。

它的!方法的定义为

def !(message: Any)(implicit sender: ActorRef = Actor.noSender) = underlying.sendMessage(message, sender)

underlying的定义为

def underlying: Cell = Unsafe.instance.getObjectVolatile(this, cellOffset).asInstanceOf[Cell]

Cell是ActorCell混入的一个特质,后者是Actor的实体部分(相对于ActorRef)。

对于underlying.sendMessage的调用,会调用ActorCell的sendMessage方法,这个方法实现于Dispatch这个trait。

def sendMessage(msg: Envelope): Unit =
try {
if (system.settings.SerializeAllMessages) {
val unwrapped = (msg.message match {
case DeadLetter(wrapped, _, _) ⇒ wrapped
case other ⇒ other
}).asInstanceOf[AnyRef]
if (!unwrapped.isInstanceOf[NoSerializationVerificationNeeded]) {
val s = SerializationExtension(system)
s.deserialize(s.serialize(unwrapped).get, unwrapped.getClass).get
}
}
dispatcher.dispatch(this, msg)
} catch handleException

虽然有些怪怪的,但是handleException是一个PartialFunction,所以语法是没问题的。

在if (system.settings.SerializeAllMessages)里的部分是根据需要把消息序列化后又反序列化了一遍,可能是为了副作用,因为这个流程中没有改变msg。

下面就走到了dispatcher.dispatch(this,msg)。

默认的Dispathcer实现是akka.dispatch.Dispatcher。其dispatch方法的实现为:

  protected[akka] def dispatch(receiver: ActorCell, invocation: Envelope): Unit = {
val mbox = receiver.mailbox
mbox.enqueue(receiver.self, invocation)
registerForExecution(mbox, true, false)
}

它把消息加入到receiver的mailbox中,然后调用registerForExecution。

  protected[akka] override def registerForExecution(mbox: Mailbox, hasMessageHint: Boolean, hasSystemMessageHint: Boolean): Boolean = {
if (mbox.canBeScheduledForExecution(hasMessageHint, hasSystemMessageHint)) { //This needs to be here to ensure thread safety and no races
if (mbox.setAsScheduled()) {
try {
executorService execute mbox
true
} catch {
case e: RejectedExecutionException ⇒
try {
executorService execute mbox
true
} catch { //Retry once
case e: RejectedExecutionException ⇒
mbox.setAsIdle()
eventStream.publish(Error(e, getClass.getName, getClass, "registerForExecution was rejected twice!"))
throw e
}
}
} else false
} else false
}

registerForExecution这个名字起得很到位,因为它的确只是"register",并不实际执行它。实际执行execution的是一个线程池,所以这个方法会调用executorService.execute(mbox)。

为什么能够执行mailbox呢?因为mailbox实现了Runnable方法。

  override final def run(): Unit = {
try {
if (!isClosed) { //Volatile read, needed here
processAllSystemMessages() //First, deal with any system messages
processMailbox() //Then deal with messages
}
} finally {
setAsIdle() //Volatile write, needed here
dispatcher.registerForExecution(this, false, false)
}
}

在上篇文章中,俺认为在设计Akka时,应该考虑提交给线程池的任务的粒度,在这个run方法中,实现上决定了这个粒度:ProcessAllSystemMessages以及processMailbox。

  @tailrec private final def processMailbox(
left: Int = java.lang.Math.max(dispatcher.throughput, 1),
deadlineNs: Long = if (dispatcher.isThroughputDeadlineTimeDefined == true) System.nanoTime + dispatcher.throughputDeadlineTime.toNanos else 0L): Unit =
if (shouldProcessMessage) {
val next = dequeue()
if (next ne null) {
if (Mailbox.debug) println(actor.self + " processing message " + next)
actor invoke next
if (Thread.interrupted())
throw new InterruptedException("Interrupted while processing actor messages")
processAllSystemMessages()
if ((left > 1) && ((dispatcher.isThroughputDeadlineTimeDefined == false) || (System.nanoTime - deadlineNs) < 0))
processMailbox(left - 1, deadlineNs)
}
}

这个方法会调用actor.invoke(next)来处理消息。

  final def invoke(messageHandle: Envelope): Unit = try {
currentMessage = messageHandle
cancelReceiveTimeout() // FIXME: leave this here???
messageHandle.message match {
case msg: AutoReceivedMessage ⇒ autoReceiveMessage(messageHandle)
case msg ⇒ receiveMessage(msg)
}
currentMessage = null // reset current message after successful invocation
} catch handleNonFatalOrInterruptedException { e ⇒
handleInvokeFailure(Nil, e)
} finally {
checkReceiveTimeout // Reschedule receive timeout
}

对于AutoReceivedMessage会走autoRecieveMessage这条路,其它的走receiveMessage(msg)这条路。

final def receiveMessage(msg: Any): Unit = actor.aroundReceive(behaviorStack.head, msg)
protected[akka] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = receive.applyOrElse(msg, unhandled)

至此,可以看到我们在actor中定义的receive方法返回的Actor.Receive这个PartialFunction被应用于msg。也就是说,至此,我们定义的处理消息的逻辑被执行。


可见,Akka处理消息的过程,实际上是就是把消息加入了actor的mailbox中,然后生成一个任务(即Mailbox的run方法中的动作)提交给线程池。

当然这其中的很多细节决定了Akka的正确工作。比如每次调用processMailbox处理多少消息;比如equeue一个消息到mailbox的动作是否阻塞,阻塞多久;比如,在Mailbox的receiveMessage方法中,behaviorStack的行为。

[Akka]发送一条消息的内部流程的更多相关文章

  1. 【转】C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1)

    C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1) #region 截获消息        /// 截获消息  处理XP不能关机问题        protected ...

  2. RabbitMQ中,exchange1绑定exchange2,exchange1和exchange2都绑定queue1,此时消息发送给exchange1,queue1中有几条消息

    如题: 存在两个交换器 exchange1,exchange2 存在一个队列 queue1 存在三个绑定关系:exchange1绑定exchange2 ,exchange1绑定queue1,excha ...

  3. [3] MQTT,mosquitto,Eclipse Paho---怎样使用 Eclipse Paho MQTT工具来发送订阅MQTT消息?

    在上两节,笔者主要介绍了 MQTT,mosquitto,Eclipse Paho的基本概念已经怎样安装mosquitto. 在这个章节我们就来看看怎样用 Eclipse Paho MQTT工具来发送接 ...

  4. C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值

    接收拦截+发送消息 对于处理所有消息.net 提供了wndproc进行重写 WndProc(ref Message m)protected override void WndProc(ref Mess ...

  5. 使用Python发送、订阅消息

    使用Python发送.订阅消息 使用插件 paho-mqtt 官方文档:http://shaocheng.li/post/blog/2017-05-23 Paho 是一个开源的 MQTT 客户端项目, ...

  6. 掌握Rabbitmq几个重要概念,从一条消息说起

    RabbitMQ 是功能强大的开源消息代理.根据官网称:也是使用量最广泛的消息队列.就像他的口号“Messaging that just works”,开箱即用使用简单,支持多种消息传输协议(AMQP ...

  7. PHP版微信公共平台消息主动推送,突破订阅号一天只能发送一条信息限制

    2013年10月06日最新整理. PHP版微信公共平台消息主动推送,突破订阅号一天只能发送一条信息限制 微信公共平台消息主动推送接口一直是腾讯的私用接口,相信很多朋友都非常想要用到这个功能. 通过学习 ...

  8. 源码分析Kafka 消息拉取流程

    目录 1.KafkaConsumer poll 详解 2.Fetcher 类详解 本节重点讨论 Kafka 的消息拉起流程. @(本节目录) 1.KafkaConsumer poll 详解 消息拉起主 ...

  9. nsq - 一条消息的生命周期(一)

    经过前面几篇的学习,相信大家对nsq已经有了一个大概的了解,我在写这篇文章的时候也看了很多其他人写的教程,发现大家对于分析系统每个点写的很不错,但是都很少有整体串起来一起走一遍,所以,我打算分成2-3 ...

随机推荐

  1. Windows7 下配置添加ASP功能

    按照如下顺序添加 1.控制面板-程序-打开或关闭Windows功能 2.Internet信息服务-万维网服务-应用程序开发功能 3.勾选ASP 和ASP.net选项 确定后安装完毕即可支持.

  2. button按钮在IE6、7、8、9、10中处理方式并不相同[转]

    http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx 转自:http://my.oschina.net/fz04003/ ...

  3. 通过使用Chrome的开发者工具来学习JavaScript

    本文作者是Peter Rybin,Chrome开发者工具团队成员. 本文中,我们将通过使用Chrome的开发者工具,来学习JavaScript中的两个重要概念”闭包”和”内部属性”. 闭包 首先要讲的 ...

  4. 【leetcode】7. Reverse Integer

    题目描述: Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 解题思 ...

  5. dorado listener属性

    每一个控件都有一个listener属性,可以用来定位一个服务定位表达式,通过这个表达式, 它最终可以映射为spring里面一个javaBean的一个java方法 例如设置DynaView1.view. ...

  6. linux之gdb使用

    gdb是linux下用来调试的一款软件,在这里,我只记录平常经常会用到的知识点,用到什么,就记录什么,在调试环境中去熟悉调试方法和调试工具,这才会加深理解. gdb能够做什么?它可以按照你的定义,随心 ...

  7. 进度条轮播【BackgroundColor】

    直接贴代码先看 HTML: <div class="bannar"> <div class="img"> <ul> < ...

  8. sqlite3简单使用

    下载SQLite3 地址:http://www.sqlite.org/download.html 下载好的文档是SQlite3.exe,假如放在D盘. cmd D: D:\>SQlite3.ex ...

  9. 将C# dataTable 做为参数传入到存储过程

    1.list转换为DataTable(如果有需要) public static DataTable ListToDataTable<T>(List<T> entitys) { ...

  10. 关于C#正则表达式MatchCollection类的总结,正则表达式的应用

    认识MatchCollection 类 表示通过以迭代方式将正则表达式模式应用于输入字符串所找到的成功匹配的集合. 命名空间:  System.Text.RegularExpressions 属性:C ...