本将主要内容:
1. actor引用、actor路径
下图是akka官方文档中给出的一张图

该图清晰地说明了actorpath,actorref,actor及actorsystem之间的关系,并说明了actor整体的层次结构。前面我们提到,akka应用程序会持有一个名称为user的actor,该actor被称为guardian supervisor(守卫监督器),无论是actorsystem创建的actor还是通过actorcontext创建的actor都为user的子类,它是最顶级的actor。
对于actorref,我们已经很熟悉了,通过调用actorsystem.actorof方法可以创建actor,返回的便是actorref,例如代码
返回的便是firstactor的actorref对象,actorref最重要的作用便是向actor发送消息,例如
另外,还可以通过context隐式对象获取父actor和子actor的actorref,示例代码如下:
代码运行结果
代码
中,使用
获取myactor 的直接父actor的actorref,在本例中为firstactor,因为在firstactor中,我们使用
创建了myactor,firstactor便自动成为myactor的直接supervisor。如此便可以通过代码
发送消息。
另外,还可以通过
system.actorselection(myactorpath)方法获取相应的actorref。然后再使用获取到的actorref向acto发送消息
现在,让我们来总结一下获取actorref的方法:
(1)通过actorsystem的actorof方法,不过这种方式是通过创建actor,然后返回其actorref
(2)通过context.actorof方法,这种方式也是通过创建actor,然后返回其actorref
(3)通过context.parent、context.self、context.children方法获取当前actor的父actor、当前actor及子actor的actorref,这种方式是获取已经创建好的actor的actorref
(4)通过val myactor1=system.actorselection(myactorpath)方法来获取actorref,这种方式也是获取已经创建好的actor的actorref
在前面的例子中,我们通过
已经使用到了actorpath。在akka中,actorpath采用统一资源定位符的方式进行组织,例如
本地actorpath是akka并发编程中的actorpath表示方式,而远程actorpath是akka分布式编程中常用的actorpath表示方式,”akka.tcp://[email protected]:5678/user/service-b”中的tcp表示使用的是tcp协议,也可以使用upd协议,使用udp协议的远程actorpath表示方式有如下形式
actorpath当中,akka.udp表示的是使用的协议,my-sys表示的是actorsytem名称,host.example.com:5678为远程机器地址及端口,user为guardian supervisor,service-b为当前应用程序的顶级actor(通过system.actorof方法创建的)
代码运行结果:
本例中的重点代码如下
通过 val firstactorpath=system.child(“firstactor”)构造一个actorpath,然后使用
获取路径下的actorref,除这种方式外,还可以通过绝对路径 val myactor2=system.actorselection(“/user/firstactor”)及相对路径 val myactor3=system.actorselection(“../firstactor”)的方式获取actorref
,需要注意的是绝对路径使用的是guardian supevisor,即/user/firstactor的这种方式。
如果要获取myactor,则基方法是类型的,例如
完整代码如下:
关于远程actorref的获取,我们将在后续章节中进行讲述。
scala学习(公众微信号:scalalearning)每天为大家带来一点scala语言、spark、kafka、flink、akka等大数据技术干货及相关技术资讯。技术永无止境,勇攀高峰,一往直前!
觉得文章不错?扫描关注