使用 Akka 时不匹配的消息会怎样?

What happens to unmatched messages with Akka?

A​​kka 文档说不会扫描邮箱中的邮件。每条消息按到达顺序依次处理(默认为 FIFO)。但是,当我将一条消息从一个演员发送到另一个与接收演员不匹配的演员时,它既不会移动到死信演员(我想这会出现在日志中),也不会阻止处理邮箱中的下一条消息一秒后到达,可以正确处理。

邮箱中的不匹配邮件会怎样?

我在 sbt 中使用 Scala 2.10.4 和 Akka 2.4-SNAPSHOT。

package main.scala

import akka.actor._

class SRActor(dest: ActorRef) extends Actor with ActorLogging {
  dest ! A
  dest ! B

  context.stop(self)

  override def receive = {
    case _ => {
      log.info("Finally got something")
    }
  }
}

class SRActorReceiver extends Actor with ActorLogging {
  override def receive = {
    case B =>
      log.info("Finally got B")
  }
}

演员创作:

package main.scala

import akka.actor._
case object A
case object B

object ErrorApp extends App {
// SR: Send nowhere received
  var system6 = ActorSystem("ErrorActorSystem")
  val srActorReceiver = system6.actorOf(Props(classOf[SRActorReceiver]), "sractorreceiver")
  val sractor = system6.actorOf(Props(classOf[SRActor], srActorReceiver), "sractor")

  // wait until actors have finished
  Thread.sleep(1000)

  system6.shutdown

复制自docs

Please note that the Akka Actor receive message loop is exhaustive, which is different compared to Erlang and the late Scala Actors. This means that you need to provide a pattern match for all messages that it can accept and if you want to be able to handle unknown messages then you need to have a default case as in the example above. Otherwise an akka.actor.UnhandledMessage(message, sender, recipient) will be published to the ActorSystem's EventStream.

Actor 特征中还有 unhandled 方法,您可以覆盖它。 (docs)

def unhandled(message: Any): Unit

User overridable callback.

Is called when a message isn't handled by the current behavior of the actor by default it fails with either a akka.actor.DeathPactException (in case of an unhandled akka.actor.Terminated message) or publishes an akka.actor.UnhandledMessage to the actor's system's akka.event.EventStream