akka unstashAll()没有重播消息

时间:2017-07-25 14:07:29

标签: scala akka actor

我有这个:

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()被调用但是我没有收到消息:{{ 1}}任何原因?

2 个答案:

答案 0 :(得分:1)

我建议在处理任何消息之前调用preStart(),将数据库初始化和unstash / become代码移动到单独的消息(比如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

答案 1 :(得分:0)

这一定必须发生,因为你的演员在你的演员成为connectedReceive之前已经收到毒药。 在毒丸的情况下,演员不会隐藏信息,只会自杀。