本節主要內容
當Typed Actor不再需要時要將其停止,有3種方法停止Typed Actor的運行:
(1)通過system.shutdown()停止ActorSystem中所有的Typed Actor;
(2)調用TypedActor(system).stop(mySquarer)停止指定的Typed Actor;
(3)調用TypedActor(system).poisonPill(otherSquarer)停止指定的Typed Actor。
具體使用代碼以下:
/*
* 停止Typed Actor
*/
object Example_3 extends App {
import akka.event.Logging
import scala.concurrent.{ Promise, Future }
import akka.actor.{ TypedActor, TypedProps }
import scala.concurrent.duration._
trait Squarer {
//fire-and-forget消息
def squareDontCare(i: Int): Unit
//非阻塞send-request-reply消息
def square(i: Int): Future[Int]
//阻塞式的send-request-reply消息
def squareNowPlease(i: Int): Option[Int]
//阻塞式的send-request-reply消息
def squareNow(i: Int): Int
}
//混入PostStop和PreStart
class SquarerImpl(val name: String) extends Squarer with PostStop with PreStart {
import TypedActor.context
val log = Logging(context.system,TypedActor.self.getClass())
def this() = this("SquarerImpl")
def squareDontCare(i: Int): Unit = i * i
def square(i: Int): Future[Int] = Promise.successful(i * i).future
def squareNowPlease(i: Int): Option[Int] = Some(i * i)
def squareNow(i: Int): Int = i * i
def postStop(): Unit={
log.info ("TypedActor Stopped")
}
def preStart(): Unit={
log.info ("TypedActor Started")
}
}
val system = ActorSystem("TypedActorSystem")
val log = Logging(system, this.getClass)
//使用默許構造函數創建Typed Actor
val mySquarer: Squarer =
TypedActor(system).typedActorOf(TypedProps[SquarerImpl](),"mySquarer")
//使用非默許構造函數創建Typed Actor
val otherSquarer: Squarer =
TypedActor(system).typedActorOf(TypedProps(classOf[Squarer],
new SquarerImpl("SquarerImpl")), "otherSquarer")
//Request-reply-with-future 消息發送
val fSquare = mySquarer.square(10)
val result = Await.result(fSquare, 5 second)
log.info("fSquare="+result)
//調用poisonPill方法停止Actor運行
TypedActor(system).poisonPill(otherSquarer)
//調用stop方法停止Actor運行
TypedActor(system).stop(mySquarer)
//system.shutdown()
}
代碼運行結果以下所示。
[INFO] [03/21/2016 22:41:51.119] [TypedActorSystem-akka.actor.default-dispatcher-2] [$Proxy0(akka://TypedActorSystem)] TypedActor Started
[INFO] [03/21/2016 22:41:51.123] [TypedActorSystem-akka.actor.default-dispatcher-2] [$Proxy1(akka://TypedActorSystem)] TypedActor Started
[INFO] [03/21/2016 22:41:51.124] [main] [Example12_10$(akka://TypedActorSystem)] fSquare=100
[INFO] [03/21/2016 22:41:51.131] [TypedActorSystem-akka.actor.default-dispatcher-5] [$Proxy1(akka://TypedActorSystem)] TypedActor Stopped
[INFO] [03/21/2016 22:41:51.131] [TypedActorSystem-akka.actor.default-dispatcher-3] [$Proxy0(akka://TypedActorSystem)] TypedActor Stopped
代碼中類SquarerImpl 混入了PreStart和PostStop兩個trait:class SquarerImpl(val name: String) extends Squarer with PostStop with PreStart,這樣的話在創建TypedActor之前和停止TypedActor后能夠進行相應的操作,本例中主要是為監視TypedActor的創建和停止進程。代碼TypedActor(system).stop(mySquarer)通過stop方法停止TypedActor,而TypedActor(system)
.poisonPill(otherSquarer)通過調用poisonPill方法停止運行TypedActor。