akka 我如何才能获得演员已被解雇的信息?

gajydyqb  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(126)

假设我有一个根参与者(不是由另一个参与者创建的,而是由其他地方创建的),我如何监视这个参与者?我如何获得参与者被终止的信息?

42fyovps

42fyovps1#

最好创建一个父参与者,并使用actorSelection生成一个子参与者,您可以观看。创建子参与者后,您可以使用context.watch(child)观看它。然后,一旦您有了这个子参与者,您就可以发送一个PoisonPill来检查这个参与者是否还活着。下面是一个简单的示例:

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] 
...

相关问题