2017-07-25 75 views
1

我有這個不是重播的消息:阿卡unstashAll()

val receive = beforeLoadReceive // my default receive 

override def preStart(): Unit = { 
    doSomeLoadFromDB() 
    unstashAll() 
    context.become(connectedReceive) 
    println("I also get to here..." 
} 

def connectedReceive: Receive = { 
    case GetData => 
     println("for some reason i'm not getting to here after unstashAll why?") 
     sender() ! "this is your data" 
} 

def beforeLoadReceive: Receive = { 
    case GetData => 
     println(s"I get to here so it's stashed") 
     stash() 
} 

所以我使用的stash()我看到,我得到一個消息,有這樣的藏,我也看到事後說unstashAll()的調用,但我不明白:connectedReceive的任何原因?

回答

1

我建議在處理任何消息之前調用preStart()方法來調用DB初始化和取消/成爲代碼到單獨的消息(如InitDB)處理程序。如預期以下作品的代碼:

object GetData 
object InitDB 

class ReporterActor extends Actor { 
    val dbActor = context.system.actorOf(Props(new DbActor())) 

    override def preStart(): Unit = { 
    super.preStart() 
    dbActor ! GetData 
    } 

    def receive = { 
    case m: String => { 
     println("Received: " + m) 
     context.system.terminate() 
    } 
    } 
} 

class DbActor extends Actor with Stash { 
    val receive = beforeLoadReceive // my default receive 

    override def preStart(): Unit = { 
    self ! InitDB 
    } 

    def connectedReceive: Receive = { 
    case GetData => 
     println("for some reason i'm not getting to here after unstashAll why?") 
     sender() ! "this is your data" 
    } 

    def beforeLoadReceive: Receive = { 
    case InitDB => 
     // doSomeLoadFromDB() 
     Thread.sleep(5000) 
     context.become(connectedReceive) 
     unstashAll() 
     println("I also get to here...") 

    case GetData => 
     println(s"I get to here so it's stashed") 
     stash() 
    } 
} 

val as = ActorSystem() 
val actor = as.actorOf(Props(new ReporterActor())) 

Await.result(as.whenTerminated, 10.seconds) 

輸出:

I get to here so it's stashed 
I also get to here... 
for some reason i'm not getting to here after unstashAll why? 
Received: this is your data 
0

這一定是因爲你的演員在你的演員變成connectedReceive之前收到毒丸。 如果有毒丸,演員將不會隱藏信息,並會簡單地殺死自己。