2014-10-01 50 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 => 
}