1 “Killing”an actor
随着摄入挖掘Akka sctors,你将会接触到一个概念“supervisor strategies”。当你实施这个策略的时候,你将会发送一个Kill message,这个操作实际上就是用来restart an actor。在Akka documentation描述:向一个actor发送Kill message,"将会通过regular supervisor 语义"restart actor.。
2 Shutting Down the Akka Actor System
当你的应用中不需要再使用actor时,你需要对actorSystem实例使用shutdown方法
对actorsSystem使用shutdown方法:
object Main extends App {
// create the ActorSystem
val system = ActorSystem("HelloSystem")
// put your actors to work here ...
// shut down the ActorSystem when the work is finished
system.shutdown
}
3 Monitoring the Death of an Actor with watch
注:actor出现异常之后重启不会被watch监测到
当其他的actor 死亡(die)时,想通知某一个actor。使用actor的context object的watch方法
在下面的例子中,Parent actor 创造了一个actor实例“kenny”,并想“watch”kenny
class Parent extends Actor {
val kenny = context.actorOf(Props[Kenny], name = "Kenny")
context.watch(kenny)
// more code here ...
(显然,kenny是一个ActorRef 实例,但是简单的被称作“actor”)
如果kenny被killed或者是stopped,Parent会接受Terminated(kenny) message
例子:
import akka.actor._
class Kenny extends Actor{
def receive={
case _ => println("Kenny received a a message")
}
}
class Parent extends Actor{
val kenny = context.actorOf(Props[Kenny],name="Kenny") //产生child actor "kenny"
context.watch(kenny)
def receive={ //kenny 死亡之后,会向Parent发送Terminated(kenny)
case Terminated(kenny) => println("OMG,they killed Kenny")
case _ => println("Parent received a message")
}
}
object DeathWatchTest {
def main(args: Array[String]): Unit = {
val system = ActorSystem("DeathWatchTest")
val parent = system.actorOf(Props[Parent],name="Parent")
val kenny = system.actorSelection("/user/Parent/Kenny") //(寻找引用)名字必须对应
kenny ! PoisonPill
Thread.sleep(5000)
system.shutdown()
}
}
控制台输出:
OMG, they killed Kenny
calling system.shutdown
4 Looking up actors
如何去寻找actor?可以用路径的方式去寻找actor
方法1:
val kenny = system.actorSelection("/user/Parent/Kenny")
可以用actorSelection 方法寻找actors(指定路径)。这个方法用于actorSystem内部。
相对路径:如果kenny有兄弟姐妹,可以用own context 去寻找
val kenny = context.actorSelection("../Kenny")
方法2:
如:在DeathWatchTest object中进行寻找
val kenny = system.actorFor("akka://DeathWatchTest/user/Parent/Kenny")
val kenny = system.actorFor(Seq("user", "Parent", "Kenny"))
相对路径:
val kenny = system.actorFor(Seq("..", "Kenny"))