如何发送Akka广播消息

How to send Akka broadcast message

我正在尝试向多个演员发送一条消息。调查使我找到了下面的代码,但它不起作用。 Broadcast 对象中 "wrapped" 的消息消失,纯字符串最终出现在死信框中。

有人能告诉我我错过了什么吗? (编辑:我在下面添加了更正)

    import akka.actor.{Actor, ActorSystem, Props}
    import akka.routing.{Broadcast, BroadcastRoutingLogic, Router}

    object RouterAndBroadcast {
      class MyRoutee extends Actor {
        override def receive: Receive = {
          case x => println(s"MyRoutee $this got message $x")
        }
      }

      def main(args: Array[String]): Unit = {
        val system = ActorSystem.create("system")
        val mr0 = system.actorOf(Props[MyRoutee])
        val mr1 = system.actorOf(Props[MyRoutee])
        val mr2 = system.actorOf(Props[MyRoutee])
/* This was the error:
        val router = new Router(BroadcastRoutingLogic())
        router.addRoutee(mr1)
        router.addRoutee(mr2) */
// This is the corrected version:
        val router = new Router(BroadcastRoutingLogic())
          .addRoutee(mr1)
          .addRoutee(mr2)

        mr1 ! "Hello number one!"
        mr2 ! "Ahoy two, me old mate!"
        router.route(new Broadcast("Listen up!"), mr0) // vanishes??
        router.route("Listen up!", mr0) // ends up in dead letters
        mr1 ! "Number one, are you still there?"
        mr2 ! "Two, where's the grog?"
        router.route(new Broadcast("Still shouting!"), mr0) // also vanishes

        Thread.sleep(5000)
        system.terminate()
      }
    }

Router.addRoutee returns 添加了路由的副本,它不会就地修改路由器,参见:

https://github.com/akka/akka/blob/b94e064a34a7f6a9d1fea55317d5676731ac0778/akka-actor/src/main/scala/akka/routing/Router.scala#L140

  /**
   * Create a new instance with one more routee and the same [[RoutingLogic]].
   */
def addRoutee(routee: Routee): Router = copy(routees = routees :+ routee)

所以试试

router = router.addRoutee(mr1).addRoutee(mr2)