Akka併發程式設計——第八節:Actor模型(七)
阿新 • • 發佈:2018-12-25
本節主要內容
停止執行Typed Actor
當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。