【问题标题】:Pattern for interruptible loops using actors使用演员的可中断循环模式
【发布时间】:2011-04-11 19:13:41
【问题描述】:

我正在设计一个从无休止的流中使用项目的actor,并且需要一种方法来控制它何时开始和停止使用消息。有没有一种通用的模式可以用演员来实现这样的可中断循环?我正在考虑让我的演员向自己发送消息。类似(伪 Scala):

class Interruptible extends Actor {
  val stream: Stream
  val running: boolean

  def receive = {
    case "start" => {
      running = true
      consumeItem
    }

    case "stop" => {
      running = false
    }

    case "consumeNext" => consumeItem
  }

  def consumeItem {
    if (running) {
      stream.getItem
      this ! "consumeNext"
    }
  }
}

这是处理事情的最佳方式吗?

谢谢!

【问题讨论】:

  • 根据我们的最新数据,Akka 在 8 核机器上每秒处理大约 300 万条消息。你确定你没有在这里过早优化吗?
  • 感谢您的回复,维克多。我将问题改写为关于设计的问题。只是想了解演员模型! Akka很棒,顺便说一句。 -D

标签: scala actor akka


【解决方案1】:

可能是这样编码的:

class Interruptible extends Actor {
  val stream: Stream

  def inactive: Receive = { // This is the behavior when inactive
    case "start" =>
      self become active
  }

  def active: Receive = { // This is the behavior when it's active
    case "stop" =>
      self become inactive
    case "next" =>
      doSomethingWith(stream.getItem)
      self ! "next"
  }

  def receive = inactive // Start out as inactive
}

干杯,

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 2017-01-07
相关资源
最近更新 更多