本文概述
在Akka中, 可以通过调用ActorContext或ActorSystem类的stop()方法来终止Actors。 ActorContext用于终止子Actor, ActorSystem用于终止顶级Actor。
actor的实际终止是异步执行的。
Akka中还有其他一些方法可以用来终止Actor。其中一些是PoisonPill, terminate()和gracefulStop()用于终止Actor。
Akka终止顶级Actor示例
你只需调用stop()方法即可终止顶级Actor。以下示例描述了stop()方法的用法。
import akka.actor.{Actor, ActorSystem, Props};
class ActorExample extends Actor{
def receive = {
case message:String => println("Message received: "+message);
case _ => println("Unknown message");
}
override def postStop(){
println("Actor stoped");
}
}
object ActorExample{
def main(args:Array[String]){
val actorSystem = ActorSystem("ActorSystem");
val actor = actorSystem.actorOf(Props[ActorExample], "RootActor");
actor ! "Hello"
actorSystem.stop(actor);
}
}
输出
Message received: Hello
Actor stoped
Akka终止子Actor的例子
import akka.actor.{Actor, ActorSystem, Props};
class ActorExample extends Actor{
def receive = {
case message:String => println("Message received by "+self.path.name+": "+message);
val childactor = context.actorOf(Props[ChildActor], "ChildActor");
childactor ! "Hello child Actor"
context.stop(childactor);
case _ => println("Unknown message");
}
}
class ChildActor extends Actor{
def receive = {
case message:String => println("Message received by "+self.path.name+": "+message);
case _ => println("Unknown message");
}
override def postStop(){
println("Child Actor stoped");
}
}
object ActorExample{
def main(args:Array[String]){
val actorSystem = ActorSystem("ActorSystem");
val actor = actorSystem.actorOf(Props[ActorExample], "RootActor");
actor ! "Hello"
}
}
输出
Message received by RootActor: Hello
Message received by ChildActor: Hello child Actor
Child Actor stoped
Akka Stopping ActorSystem示例
你可以通过调用actor的终止方法来终止它。此方法将终止守护者actor, 而后者又将递归终止其所有子actor。
import akka.actor.{Actor, ActorSystem, Props};
class ActorExample extends Actor{
def receive = {
case message:String => println("Message received by "+self.path.name+": "+message);
val childactor = context.actorOf(Props[ChildActor], "ChildActor");
childactor ! "Hello child Actor"
case _ => println("Unknown message");
}
override def postStop(){
println("Top Level Actor stoped");
}
}
class ChildActor extends Actor{
def receive = {
case message:String => println("Message received by "+self.path.name+": "+message);
case _ => println("Unknown message");
}
override def postStop(){
println("Child Actor stoped");
}
}
object ActorExample{
def main(args:Array[String]){
val actorSystem = ActorSystem("ActorSystem");
val actor = actorSystem.actorOf(Props[ActorExample], "RootActor");
actor ! "Hello"
actorSystem.terminate();
}
}
输出
Message received by RootActor: Hello
Message received by ChildActor: Hello child Actor
Child Actor stoped
Top Level Actor stoped