【问题标题】:How to get the actor system reference from inside the actor如何从actor内部获取actor系统引用
【发布时间】:2014-10-03 16:23:52
【问题描述】:

我有一个向自己发送消息的 akka 演员:

  def receive = {
    while (...) {
       self ! "some message"
    }
  }

我想使用一个 Throttler 来控制这个 Actor 发送给自己的消息流。

  val throttler = system.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
  throttler ! SetTarget(Some(self))

然后更改 while 循环以向限制器发送消息:

    while (...) {
       throttler ! "some message"
    }

问题是我不知道如何从演员内部访问“系统”来创建节流器。这个怎么做?有没有更好的办法?

【问题讨论】:

    标签: scala akka actor throttling


    【解决方案1】:

    为什么不将节流器创建为子actor?:

    def receive = {
        val throttler = context.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
        throttler ! SetTarget(Some(self))
        while (...) {
           throttler ! "some message"
        }
    }
    

    如果计算参与者死了,让 Throttler 活着是没有意义的。

    【讨论】:

      【解决方案2】:

      你可以使用context:

      val throttler = context.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
      

      【讨论】:

        【解决方案3】:

        在 Akka 中,您可以使用 Actor System 或 Actor 上下文创建 Actor,例如:

        class FirstActor extends Actor {
          val child = context.actorOf(Props[MyActor], name = "myChild")
          // plus some behavior ...
        }
        

        context 是一个可供每个 Actor 使用的变量。

        如果您使用actor Context 创建actor,它会成为创建actor 的受监督子,请参阅Akka Docs about supervisionActor Creation 了解更多信息。

        【讨论】:

          【解决方案4】:

          在actor内部,使用context.system访问ActorSystem。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-02-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多