2014-10-01 55 views

回答

1

標準的方式來實現,這將是使用Ask Pattern

它是這樣的:

class MyActor extends Actor { 
    def receive = { 
    case "Ping" => sender ! "Pong" 
    } 
} 

val future = actor ? "Ping" 
val result = Await.result(future, 10 seconds) //blocks until the response has been received, or the timeout reached 

這是假設你想從演員的消息封鎖。如果你想知道什麼時候一個演員已經死了,你需要使用臨終看護是這樣的:

case object TellMeWhenActorDies 
case object ActorDied 

class Watcher extends Actor { 
    val child = context.actorOf(Props[Watched], "watched") 
    context.watch(child) 

    override def receive: Receive = { 
    case TellMeWhenActorDies => context.become(waitingForDeath(sender)) 
    } 

    def waitingForDeath(client: ActorRef): Receive = { 
    case Terminated(name) => client ! ActorDied 
    } 
} 

class Watched extends Actor { 
    override def receive: Receive = { 
    case _ => //do nothing 
    } 
} 

val finishedFuture = supervisor ? TellMeWhenActorDies 
system.actorSelection("/user/$a/watched").tell(PoisonPill, supervisor) 
    Await.result(finishedFuture, 10 seconds) 
0

只需使用gracefulStop模式。這個例子直接來自Akka文檔:

try { 
    val stopped: Future[Boolean] = gracefulStop(actorRef, 5 seconds, Manager.Shutdown) 
    Await.result(stopped, 6 seconds) 
    // the actor has been stopped 
} catch { 
    // the actor wasn't stopped within 5 seconds 
    case e: akka.pattern.AskTimeoutException => 
}