import akka.actor.{Actor, ActorLogging, ActorSystem, PoisonPill, Props, Terminated}
object WatchingActors {
def main(args: Array[String]): Unit = {
import ParentWatcher._
val system = ActorSystem("WatchingActors")
val parentWatcherActor = system.actorOf(Props[ParentWatcher], "parentWatcher")
parentWatcherActor ! StartChild("child3")
val child3 = system.actorSelection("/user/parentWatcher/child3")
// make sure that child3 has been created
child3 ! s"[1] child3, are you still there?"
Thread.sleep(1000)
child3 ! s"[2] child3, are you still there?"
// SENDING A POISON PILL TO SIMULATE THE DEATH
child3 ! PoisonPill
for (i <- 3 to 50) child3 ! s"[$i] child3, are you still there?"
}
object ParentWatcher {
case class StartChild(name: String)
case class StopChild(name: String)
case object Stop
}
// This is a better parent actor
class ParentWatcher extends Actor with ActorLogging {
import ParentWatcher._
override def receive: Receive = {
case StartChild(name) =>
log.info(s"[ParentWatcher] Starting child $name")
val child = context.actorOf(Props[Child], name)
// WATCH THE ACTOR HERE
context.watch(child)
case Terminated(actorRef) =>
// GET THE CHILD ACTOR REFERENCE THAT JUST DIED
log.info(s"the reference that I am watching ${actorRef.path.name} has been stopped")
}
}
class Child extends Actor with ActorLogging {
override def receive: Receive = {
case message => log.info(message.toString)
}
}
}
记录档:
[1] child3, are you still there?
[2] child3, are you still there?
Message [java.lang.String] to Actor[akka://WatchingActors/user/parentWatcher/child3#1022823549] was not delivered. [1] dead letters ...
Actor[akka://WatchingActors/user/parentWatcher/child3#1022823549] was not delivered. [2] dead letters ...
....
the reference that I am watching child3 has been stopped
Message [java.lang.String] to Actor[akka://WatchingActors/user/parentWatcher/child3#1022823549] was not delivered. [6]
...
1条答案
按热度按时间42fyovps1#
最好创建一个父参与者,并使用
actorSelection
生成一个子参与者,您可以观看。创建子参与者后,您可以使用context.watch(child)
观看它。然后,一旦您有了这个子参与者,您就可以发送一个PoisonPill
来检查这个参与者是否还活着。下面是一个简单的示例:记录档: