preStart挂钩:发送给演员本身的消息 [英] preStart hook: a message to the actor itself
问题描述
假设我覆盖了 preStart
钩子,并向 self
发送了一条消息:
Let's say I override the preStart
hook and send a message to self
:
Class SomeActor extends Actor {
override def preStart(): Unit = {
self ! SomeMessage
}
...
}
我可以期望 SomeMessage
是队列中的第一条消息吗?
Can I expect that SomeMessage
will be the first message in the queue?
推荐答案
否,由于actor的创建是异步发生的,因此有人可能在构造函数或 preStart
实际运行之前就已经将消息排队。如果您需要确保先处理此消息,则需要使用成为
和隐藏
:
No, since actor creation happens asynchronously someone might have enqueued a message before the constructor or preStart
actually run. If you need to ensure processing of this message before any other then you’ll need to use become
and stash
:
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
特性,并将此actor配置为使用 DequeBasedMailbox
。
You’ll need to mix in the akka.actor.Stash
trait and configure this actor to use a DequeBasedMailbox
.
这篇关于preStart挂钩:发送给演员本身的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!