与 Scala.Actors 相比,如何正确设置 Akka.Actors

发布于 2024-12-07 05:06:55 字数 540 浏览 2 评论 0原文

如何运行 2 个 Akka Actor,调用者每 n 秒向消费者发送一条消息? 由于 Scala.Actors 库中没有循环反应方法,我陷入了困境 不知何故,以下内容将不会编译并生成:

重写方法接收类型 => 的特质 Actor 调用者.this.接收;方法接收具有不兼容的类型

object Foo {
  def init() {
    actorOf[Caller].start()
    actorOf[Consumer].start()
  }
}

class Caller extends Actor {

  def receive {
    while (true) {
      self ! "msg"
      Thread.sleep(1000)
    }
  }
}

class Consumer extends Actor {

  def receive = {
    case msg:String => doStuff()
    case e => _
  }
}

How do I run 2 Akka actors with the caller sending the consumer a message every n seconds?
As there are no loop-react methods as in the Scala.Actors library I am stuck
somehow, the following will not compile and produces:

overriding method receive in trait Actor of type =>
Caller.this.Receive; method receive has incompatible type

object Foo {
  def init() {
    actorOf[Caller].start()
    actorOf[Consumer].start()
  }
}

class Caller extends Actor {

  def receive {
    while (true) {
      self ! "msg"
      Thread.sleep(1000)
    }
  }
}

class Consumer extends Actor {

  def receive = {
    case msg:String => doStuff()
    case e => _
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陈年往事 2024-12-14 05:06:55

您在 Caller 中的 receive 之后缺少等号。如果没有它,该方法被定义为返回Unit(即没有有用的值),并且akka需要您从receive返回一个PartialFunction[Any,Unit]

现在,要以惯用的方式实际实现您的逻辑,您可能需要使用 ReceiveTimeout,如下所示:

class Caller extends Actor {
  self.receiveTimeout = Some(1000)

  def receive = { 
    case ReceiveTimeout => 
      self ! "msg"
  }
}

You're missing the equals sign after receive in Caller. Without it, the method is defined as returning Unit (i.e. no useful value), and akka needs you to return a PartialFunction[Any,Unit] from receive.

Now, to actually implement your logic in the idiomatic way, you probably want to use a ReceiveTimeout, like so:

class Caller extends Actor {
  self.receiveTimeout = Some(1000)

  def receive = { 
    case ReceiveTimeout => 
      self ! "msg"
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文