在我之前的博文中,已经介绍过要慎用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. 动态 SQL(2)

    前面我们学习了使用动态 SQL 的 if.where.trim元素来处理一些简单查询操作,但对于一些 SQL 语句中含有 in 条件,需要迭代条件集合来生成的情况,我们就需要使用 foreach 标签 ...

  2. instance_name,db_name,oracle_sid之间的关系

    一]对ORACLE_SID的理解 --------------------------------------------------------------------------------Ora ...

  3. 阿里云创建CentOS系统设置

    1 首先设置你购买的云盘配置,例如cpu,内存,磁盘类型.容量,网络类型等 2.阿里云可以使用浏览器进行远程shell连接 首先需要输入远程密码,第一次连接的时候会提示 一定要牢记 输入密码后进入sh ...

  4. 通过request对象获取客户端的相关信息

    通过request对象获取客户端的相关信息 制作人:全心全意 通过request对象可以获取客户端的相关信息.例如HTTP报头信息.客户信息提交方式.客户端主机IP地址.端口号等等. request获 ...

  5. plot3d

    plot3d plot3D a format for structured grid data that was popularized by NASA's CFD visualization Aut ...

  6. PAT 1146 Topological Order

    This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topol ...

  7. yarn & vue-cli

    yarn & vue-cli https://github.com/xgqfrms/ES6/issues/10 install https://yarnpkg.com/zh-Hans/docs ...

  8. noip模拟赛 圆桌游戏

    [问题描述] 有一种圆桌游戏是这样进行的:n个人围着圆桌坐成一圈,按顺时针顺序依次标号为1号至n号.对1<i<n的i来说,i号的左边是i+1号,右边是i-1号.1号的右边是n号,n号的左边 ...

  9. 使用java操作hbase(单节点)

    1.在运行java代码之前,一定要先启动Hbase,很重要!!    cd /home/cx/itcast/hbase-1.2.6/bin   ./start-hbase.sh 2.新建一个java项 ...

  10. xcode5下取消ARC

    打开你的工程,点击目录的工程文件,最顶端蓝色的,然后选择project下你的工程,还是蓝色那项,然后build Settings,然后往下拉,在Apple LLVM 5.0 - Language - ...