preStart hook:向actor本身发送的消息

时间:2013-05-02 12:00:28

标签: scala akka

假设我覆盖preStart挂钩并向self发送消息:

Class SomeActor extends Actor {

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

  ...

}

我可以期待SomeMessage成为队列中的第一条消息吗?

1 个答案:

答案 0 :(得分:28)

不,因为actor创建是异步发生的,所以有人可能在构造函数或preStart实际运行之前将消息排入队列。如果您需要确保在任何其他邮件之前处理此邮件,那么您需要使用becomestash

self ! SomeMessage

def receive = initial

def initial: Receive = {
  case SomeMessage =>
    // do stuff
    unstashAll()
    context become initialized
  case _ => stash()
}

def initialized: Receive = {
  // your normal behavior
}

您需要混合使用akka.actor.Stash特征并将此演员配置为使用DequeBasedMailbox