2017-06-16 47 views
0

,我有以下我演员的(我称之为演员MasterActor)接收方法的代码:停止的演员实例,并等待其停止

override def receive: Receive = { 
    case StopActor(id, actorConfig) => 
     log.info(s"Stopping actor with id = $id and config $actorConfig") 

     stopActor(id, powerPlantCfg).pipeTo(self) 
     context.become(waitForStop(sender())) 

    // Other messages... not shown here for simplicity 
    } 

那么我上面做的是停止演员并将包含上述Receive方法的Actor的结果传递给Future [Continue](其中Continue是Monix Ack类型)的结果。该stopActor看起来是这样的:

private def stopActor(id: Long, cfg: ActorConfig): Future[Ack] = async { 
    await(fetchActor(id).materialize) match { 
     case scala.util.Success(actorRef) => 
     log.info(s"Stopping Actor with id = $id") 
     context.watch(actorRef) 
     context.stop(actorRef) 
     Continue 
     case scala.util.Failure(fail) => 
     log.error(s"Could not fetch Actor instance for id = $id because of: $fail") 
     Continue 
    } 
    } 

我做的context.watch(actorRef),这是我waitForStop看起来像:

private def waitForStop(source: ActorRef): Receive = { 
    case Continue => 
     source ! Continue 
     context.become(receive) 

    case someShit => 
     log.error(s"Unexpected message $someShit received while waiting for an actor to be stopped") 
    } 

所以我有2个问题在这里:

  1. 在做context.become(waitForStop(sender()))时,我关闭了sender(),所以我假设发件人在这种情况下是ActorRef,它包含上述所有代码,它是MasterActor 。我对么?

  2. 我如何明确知道,我试图停止的这个ActorRef实际上是停止的,这样一旦它停止,我就可以做一个context.unwatch(actorRef)?

有什么建议吗?

回答

2

您可以通过观看来通知演员的停止。您已经熟悉手表:

val kenny = context.actorOf(Props[Kenny], name = "Kenny") 
context.watch(kenny) 

然后您可以等待终止消息。一旦你收到它,你可以解开你需要的东西。

def receive = { 
    case Terminated(kenny) => println("OMG, they killed Kenny") 
    case _ => println("Parent received a message") 
} 

所以我的建议是简单地看,等待终止,并发出停止命令。但我不确定你在问什么,所以这个错误将会是错误的答案。 Blog post example

+0

很酷!那么谁会发送Termintaed消息?它是否由ActorSystem发送? – sparkr

+0

@sparkr是的。这就是观看的全部内容:) –

+0

但是,在您描述或获取终止消息后,我不会发送停止命令吗? – sparkr