在我之前的博文中,已经介绍过要慎用Actor的ask。这里我们要分析一下ask的源码,看看它究竟是怎么实现的。

  开发时,如果要使用ask方法,必须要引入akka.pattern._,这样才能使用ask(或者?)方法,那么想必ask是在akka.pattern._对应的包里面实现的。

/*
* Implementation class of the “ask” pattern enrichment of ActorRef
*/
final class AskableActorRef(val actorRef: ActorRef) extends AnyVal { /**
* INTERNAL API: for binary compatibility
*/
protected def ask(message: Any, timeout: Timeout): Future[Any] =
internalAsk(message, timeout, ActorRef.noSender) def ask(message: Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] =
internalAsk(message, timeout, sender) /**
* INTERNAL API: for binary compatibility
*/
protected def ?(message: Any)(implicit timeout: Timeout): Future[Any] =
internalAsk(message, timeout, ActorRef.noSender) def ?(message: Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] =
internalAsk(message, timeout, sender) /**
* INTERNAL API: for binary compatibility
*/
private[pattern] def internalAsk(message: Any, timeout: Timeout, sender: ActorRef) = actorRef match {
case ref: InternalActorRef if ref.isTerminated ⇒
actorRef ! message
Future.failed[Any](new AskTimeoutException(s"""Recipient[$actorRef] had already been terminated. Sender[$sender] sent the message of type "${message.getClass.getName}"."""))
case ref: InternalActorRef ⇒
if (timeout.duration.length <= 0)
Future.failed[Any](new IllegalArgumentException(s"""Timeout length must be positive, question not sent to [$actorRef]. Sender[$sender] sent the message of type "${message.getClass.getName}"."""))
else {
val a = PromiseActorRef(ref.provider, timeout, targetName = actorRef, message.getClass.getName, sender)
actorRef.tell(message, a)
a.result.future
}
case _ ⇒ Future.failed[Any](new IllegalArgumentException(s"""Unsupported recipient ActorRef type, question not sent to [$actorRef]. Sender[$sender] sent the message of type "${message.getClass.getName}"."""))
} }

  上面是通过定位ask(或?)找到的实现源码,我们发现,这是一个隐式转换,在akka.pattern.AskSupport中我们找到了隐式转换对应的函数。

implicit def ask(actorRef: ActorRef): AskableActorRef = new AskableActorRef(actorRef)

  通过AskableActorRef源码我们知道最终调用了internalAsk函数,该函数有三个参数:待发送的消息、超时时间、消息发送者。函数创建了一个PromiseActorRef,又把消息原样的通过原actor的tell函数发送给了原actor,然后用新创建的PromiseActorRef作为新的sender传递,再用PromiseActorRef的result.future作为最终的Future返回。下面我们来看一下PromiseActorRef的创建过程。

def apply(provider: ActorRefProvider, timeout: Timeout, targetName: Any, messageClassName: String,
sender: ActorRef = Actor.noSender, onTimeout: String ⇒ Throwable = defaultOnTimeout): PromiseActorRef = {
val result = Promise[Any]()
val scheduler = provider.guardian.underlying.system.scheduler
val a = new PromiseActorRef(provider, result, messageClassName)
implicit val ec = a.internalCallingThreadExecutionContext
val f = scheduler.scheduleOnce(timeout.duration) {
result tryComplete Failure(
onTimeout(s"""Ask timed out on [$targetName] after [${timeout.duration.toMillis} ms]. Sender[$sender] sent message of type "${a.messageClassName}"."""))
}
result.future onComplete { _ ⇒ try a.stop() finally f.cancel() }
a
}

  很明显,PromiseActorRef持有了一个Promise[Any],但是上面的代码只显示了在超时的时候通过onTimeout赋了值,并没有不超时赋值的逻辑,且Promise[Any]一旦完成就调用PromiseActorRef的stop方法和cancel方法。那么成功时赋值的逻辑应该在哪里呢?

  如果你对ask的使用方式比较熟悉的话,一定会找出其中的端倪的。我们来梳理一下这其中的使用细节。其实,在ask的使用与tell,并没有太大的区别,至少对于server端的Actor来说没有任何区别,都是正常的接收消息,然后处理,最后通过sender把消息使用tell返回。在ask时,消息的sender是什么,就是PromiseActorRef啊,那PromiseActorRef的!方法具体怎么实现的呢?

override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = state match {
case Stopped | _: StoppedWithPath ⇒ provider.deadLetters ! message
case _ ⇒
if (message == null) throw InvalidMessageException("Message is null")
if (!(result.tryComplete(
message match {
case Status.Success(r) ⇒ Success(r)
case Status.Failure(f) ⇒ Failure(f)
case other ⇒ Success(other)
}))) provider.deadLetters ! message
}

  很明显,接收消息的Actor会通过!返回对应的消息,消息的处理一般会命中 case other,这其实就是给result赋值,在超时之前的赋值。如果在!方法内部给result赋值的时候,刚好已经超时或已经赋过值,会把返回的消息发送给deadLetters。

  其实result,也就是Promise[Any]的赋值逻辑已经解释清楚。不过如果小伙伴对Promise不熟悉的话,此处还是有点难理解的。如果说Future是一个只读的,值还没计算的占位符。那么Promise就是一个可写的,单次指派的容器,也就是说Promise一旦赋值,就无法再次赋值,且与之关联的future也就计算完毕,返回的值就是固定的。当然了通过ask(也就是?)返回的还只是一个future,如果要取出future最终的值,还是需要Await.ready等语义来支持的,这里就不再详细解释了。

Akka源码分析-ask模式的更多相关文章

  1. 鸿蒙内核源码分析(工作模式篇) | CPU是韦小宝,七个老婆 | 百篇博客分析OpenHarmony源码 | v36.04

    百篇博客系列篇.本篇为: v36.xx 鸿蒙内核源码分析(工作模式篇) | CPU是韦小宝,七个老婆 | 51.c.h .o 硬件架构相关篇为: v22.xx 鸿蒙内核源码分析(汇编基础篇) | CP ...

  2. Akka源码分析-Akka-Streams-概念入门

    今天我们来讲解akka-streams,这应该算akka框架下实现的一个很高级的工具.之前在学习akka streams的时候,我是觉得云里雾里的,感觉非常复杂,而且又难学,不过随着对akka源码的深 ...

  3. Akka源码分析-Cluster-Metrics

    一个应用软件维护的后期一定是要做监控,akka也不例外,它提供了集群模式下的度量扩展插件. 其实如果读者读过前面的系列文章的话,应该是能够自己写一个这样的监控工具的.简单来说就是创建一个actor,它 ...

  4. Akka源码分析-Cluster-Distributed Publish Subscribe in Cluster

    在ClusterClient源码分析中,我们知道,他是依托于“Distributed Publish Subscribe in Cluster”来实现消息的转发的,那本文就来分析一下Pub/Sub是如 ...

  5. Akka源码分析-Persistence

    在学习akka过程中,我们了解了它的监督机制,会发现actor非常可靠,可以自动的恢复.但akka框架只会简单的创建新的actor,然后调用对应的生命周期函数,如果actor有状态需要回复,我们需要h ...

  6. Akka源码分析-local-DeathWatch

    生命周期监控,也就是死亡监控,是akka编程中常用的机制.比如我们有了某个actor的ActorRef之后,希望在该actor死亡之后收到响应的消息,此时我们就可以使用watch函数达到这一目的. c ...

  7. Akka源码分析-Cluster-ActorSystem

    前面几篇博客,我们依次介绍了local和remote的一些内容,其实再分析cluster就会简单很多,后面关于cluster的源码分析,能够省略的地方,就不再贴源码而是一句话带过了,如果有不理解的地方 ...

  8. Akka源码分析-Akka Typed

    对不起,akka typed 我是不准备进行源码分析的,首先这个库的API还没有release,所以会may change,也就意味着其概念和设计包括API都会修改,基本就没有再深入分析源码的意义了. ...

  9. Akka源码分析-Cluster-Singleton

    akka Cluster基本实现原理已经分析过,其实它就是在remote基础上添加了gossip协议,同步各个节点信息,使集群内各节点能够识别.在Cluster中可能会有一个特殊的节点,叫做单例节点. ...

随机推荐

  1. eclipse 中为 java 项目生成 API 文档、JavaDoc

    当我们的项目很大,编写了很多代码的时候,就需要生成一个标准的 API 文档,让后续的开发人员,或者合作者可以清晰的了解您方法的使用. 1.点击 eclipse 的 Project 菜单,选择 Gene ...

  2. Haoop Mapreduce 中的FileOutputFormat类

    FileOutputFormat类继承OutputFormat,需要提供所有基于文件的OutputFormat实现的公共功能,主要有以下两点: (1)实现checkOutputSpecs方法 chec ...

  3. CentOS7 安装 PHP7.2

    点击查看原文 安装源 安装 EPEL 软件包: $ sudo yum install epel-release 安装 remi 源: $ sudo yum install http://rpms.re ...

  4. web视频播放插件:Video For Everybody

    相比其它的web视频播放插件(video.js , jwplayer等)来说,Video For Everybody(极力推荐)是一款更好的视频播放插件,无需任何下载,支持html5以及flash播放 ...

  5. Jmeter BeanShell PreProcessor使用笔记

    打印log log.info("content:" + content); 将字符串转化为JsonString import com.alibaba.fastjson.JSON; ...

  6. 【Codeforces 600C】Make Palindrome

    [链接] 我是链接,点我呀:) [题意] 题意 [题解] 计算出来每个字母出现的次数. 把字典序大的奇数出现次数的字母换成字典序小的奇数出现次数的字母贪心即可. 注意只有一个字母的情况 然后贪心地把字 ...

  7. ansible roles例子

    #理解 changed_when failed_when become become_user ansible_become ansible_become_user static #检查group_v ...

  8. 解决使用myeclipse电脑卡的问题

    1. 原因:myeclipse会自动更新,因此会占用大量内存 2. 解决方法: (1)window->Perferences->General->Startup and Shutdo ...

  9. [bzoj1833][ZJOI2010]数字计数(数位DP)

    题目:http://www.lydsy.com:808/JudgeOnline/problem.php?id=1833 分析:简单的数位DP f[i][j][k]表示在i位数.最高位j的所有数字中k的 ...

  10. 1267 老鼠的旅行 2012年CCC加拿大高中生信息学奥赛

    1267 老鼠的旅行  2012年CCC加拿大高中生信息学奥赛 题目描述 Description You are a mouse that lives in a cage in a large lab ...