加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 在能够处理其他消息之前初始化actor

发布时间:2020-12-16 19:10:19 所属栏目:安全 来源:网络整理
导读:我有一个演员创造另一个: class MyActor1 extends Actor { val a2 = system actorOf Props(new MyActor(123))} 第二个actor必须在创建后自行初始化(bootstrap),并且只有在此之后它必须能够完成其他工作. class MyActor2(a: Int) extends Actor { //initiali
我有一个演员创造另一个:

class MyActor1 extends Actor {
  val a2 = system actorOf Props(new MyActor(123))
}

第二个actor必须在创建后自行初始化(bootstrap),并且只有在此之后它必须能够完成其他工作.

class MyActor2(a: Int) extends Actor {
  //initialized (bootstrapped) itself,potentially a long operation 
  //how?
  val initValue = // get from a server

  //handle incoming messages
  def receive = {
    case "job1" => // do some job but after it's initialized (bootstrapped) itself
  }
}

因此,MyActor2必须做的第一件事就是做一些初始化工作.这可能需要一些时间,因为它是对服务器的请求.只有在成功完成后,它才能通过接收处理传入的消息.在那之前 – 它不能那样做.

当然,对服务器的请求必须是异步的(最好是使用Future,而不是异步,等待或其他高级别的东西,如AsyncHttpClient).我知道如何使用Future,但这不是问题.

我该如何确保?

附:我的猜测是它必须首先向自己发送消息.

解决方法

您可以使用become方法在初始化后更改actor的行为:

class MyActor2(a: Int) extends Actor {

  server ! GetInitializationData

  def initialize(d: InitializationData) = ???

  //handle incoming messages
  val initialized: Receive = {
    case "job1" => // do some job but after it's initialized (bootstrapped) itself
  }

  def receive = {
    case d @ InitializationData =>
      initialize(d)
      context become initialized
  }
}

请注意,此类actor将在初始化之前删除所有消息.您必须手动保留这些消息,例如使用Stash

class MyActor2(a: Int) extends Actor with Stash {

  ...

  def receive = {
    case d @ InitializationData =>
      initialize(d)
      unstashAll()
      context become initialized
    case _ => stash()
  }
}

如果您不想使用var进行初始化,可以使用InitializationData创建初始化行为,如下所示:

class MyActor2(a: Int) extends Actor {

  server ! GetInitializationData

  //handle incoming messages
  def initialized(intValue: Int,strValue: String): Receive = {
    case "job1" => // use `intValue` and `strValue` here
  }

  def receive = {
    case InitializationData(intValue,strValue) =>
      context become initialized(intValue,strValue)
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读