Actor是Akka应用程序的基础,为分布式提供了抽象,为大规模容错的应用提供了基础。Actor对象封装了状态和行为,一个Actor通过发送消息改变另一个Actor的状态。以Actor模型的角度来看,actor是一个接收消息的计算单元,并且也可以向其他Actor发送消息。mailbox构建起来Actor之间通信的桥梁。

Actor的生命周期包括:启动、消息处理和终止。此外,actor还可以通过钩子(hook)来管理状态。如:preStart(),postStop(), preRestart()和postRestart().

Actor of Akka

一、Actor启动

1.actor的定义。

自己定义一个Actor类需要继承actor并实现处理消息的抽象方法。

class MyActor extends Actor{
  def receive = {
  }
}

2.actor的创建。

actor可以在actor系统的上下文或另一个actor上下文中创建。Akka为actor的创建提供另一个构造方法Props,可以对actor的初始化进行不同设置。初始化如下:

val system = Actorsystem("MyActorSystem")
val myActor = system.actorOf(Props[MyActor], name = "myActor")

当然也可以使用自己的构造函数

class MyActor(initialise:Int) extends Actor {
  def receive = {
  }
}

val system = ActorSystem("MyActorSystem")
val myActor = system.actorOf(Props(new MyActor(10)), name = "MyActor")

在接收处理消息之前,actor可以实现preStart()方法来处理初始化的一些需求。

override def preStart() = {
//Initialise the resources to be used by actor e.g. db
//connection opening
}

二、消息模型

Actor状态的回应基于actor收到的消息。所有传递的消息都是不可变的。

1.消息的发送。

消息的发送有两种模式:Fire and forget和Send and receive。如下图

Actor of Akka

Fire and forget是单向的,发送者发送后便不管消息。

actor ! msg

Send and receive是双向的,发送者发送后期待一个回应。

2.消息的接收和回复

def receive = {
  case message:String =>
  sender ! (message + "world")
}

三、Actor终止

终止不需要的Actor可以释放资源,所以终止也是必须的。Actor终止的流程如下:

Actor停止处理邮箱里的消息->Actor给子Actor发送终止消息->Actor等待子Actor结束的消息->Actor终止自己。

终止自己的时候,先进行postStop()处理,丢掉邮箱中的消息,打印终止消息,告知监控者已经终止。

可以用以下方法进行终止

//first option of shutting down the actors by shutting down
//the ActorSystem
system.shutdown()
//second option of shutting down the actor by sending a
//poisonPill message
actor ! PoisonPill
//third option of shutting down the actor
context.stop(self)
//or
context.stop(childActorRef)

参考文献

[1]:Akka essentials by Munish K. Gupta

分类:

技术点:

相关文章: