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

时间:2017-08-08 17:32:11

标签: akka

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

preStart内发送消息会导致临时sender引用(因为Actor尚未启动?)。所以回复可能是一纸空文。

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

2 个答案:

答案 0 :(得分:2)

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

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
  }
}

如本answer所述,如果您希望演员在处理所有其他消息之前发送消息,那么您可以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
}

答案 1 :(得分:1)

你的前提确实不正确:当preStart运行时,actor已经完全启动,它的self引用永远不是临时的。但是,如果没有代码,就无法进一步帮助你。