使用真实(非临时)发送者 ActorRef 在 Actor 启动时发送消息?



我希望演员在启动时发送消息,稍后再收到回复。

preStart内部发送消息会导致临时sender引用(因为 Actor 尚未启动?因此,答复很可能是一纸空文。

任何提示将不胜感激。如果我的前提被误导,请道歉 - 我是 Akka 的新手。

一种方法是在preStart中向self发送消息:

class MyActor extends Actor {
def preStart(): Unit = {
self ! CallService
}
def receive = {
case CallService =>
(service ? ServiceRequest).mapTo[ServiceResponse].pipeTo(self)
case ServiceResponse =>
// do something with the response
}
}

如本答案所述,如果您希望参与者在处理所有其他消息之前发送消息,则可以stash其他消息:

class MyActor extends Actor with Stash {
def preStart(): Unit = {
self ! CallService
}
def uninitialized: Receive = {
case CallService =>
(service ? ServiceRequest).mapTo[ServiceResponse].pipeTo(self)
unstashAll()
context.become(initialized)
case _ => stash() // if we get a message other than CallService, stash it
}
def initialized: Receive = {
case ServiceResponse =>
// do something with the response from the service
case ...
}
def receive = uninitialized
}

你的前提确实不正确:当 preStart 运行时,actor 已经完全启动,它self引用从来都不是临时的。但是,没有代码,就不可能进一步帮助您。

发件人应始终被视为"临时"——例如,请参阅此博客文章:

该规则只是永远不会关闭 可能在另一个线程中执行的代码,例如 计划任务或未来。诀窍是捕获当前发送者 在瓦尔中,如下图所示...

-- 在接收中关闭 Akka Actor 发送者

制作发件人的副本,然后当您准备好回复时,回复该副本 actorRef 而不是"发件人"。

最新更新