akka unstashAll() 不重播消息

akka unstashAll() not replaying the messages

我有这个:

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 有什么原因吗?

这一定会发生,因为你的演员在成为 connectedReceive 之前就已经中毒了。 在毒丸的情况下,演员不会隐藏消息,只会自杀。

我建议将数据库初始化和 unstash/become 代码移动到单独的消息(例如 InitDB)处理程序,因为在处理任何消息之前调用 preStart()。下面的代码按预期工作:

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