我寫了這個代碼爲什麼我的演員創造了2次
class TestActor extends Actor {
override def preStart(): Unit = {
println("going to start my test actor")
}
override def postStop(): Unit = {
println("came inside stop")
}
def receive = {
case msg: TestMessage => sender ! s"Hello ${msg.name}"
}
}
object TestActor {
val props = Props(new TestActor)
case class TestMessage(name: String)
}
我把它用這個客戶端代碼
object MyApp extends App {
val ac = ActorSystem("TestActorSystem")
val a = new ClassA(ac).sayHello()
val b = new ClassB(ac).sayHello()
for {
msg1 <- a
msg2 <- b
} {
println(msg1)
println(msg1)
}
Await.result(ac.terminate(), Duration.Inf)
}
class ClassA(ac: ActorSystem) {
def sayHello(): Future[String] = {
implicit val timeout = Timeout(5 seconds)
val actor = ac.actorOf(TestActor.props)
val msg = actor ? TestActor.TestMessage("foo")
msg.map(_.asInstanceOf[String])
}
}
class ClassB(ac: ActorSystem) {
def sayHello() : Future[String] = {
implicit val timeout = Timeout(5 seconds)
val actor = ac.actorOf(TestActor.props)
val msg = actor ? TestActor.TestMessage("bar")
msg.map(_.asInstanceOf[String])
}
}
我看到輸出
going to start my test actor
going to start my test actor
Hello foo
Hello foo
came inside stop
came inside stop
我的問題是,在同伴對象中,我創建了prop對象作爲val,因此只有1個val,而1 val有1個實例0
在客戶端中,兩個類都使用了actor系統的相同實例。因此應該只有一個演員,並且來自classA和ClassB的兩條消息應該已經到了同一個演員。
但似乎這兩個類都有自己的Actor實例。
'Props(new TestActor)'應該做什麼?我很難理解你想要使用哪個'Props'構造函數。另外,每次調用'system.actorOf'都會創建該actor的新實例。如果你只想創建一次你的actor,那麼你可以在'ClassB'和'ClassA'之外創建它,並將它傳遞給它們,就像你使用ActorSystem一樣。 – mfirry