context.become 改变 Akka Actor 的行为

context.become changes the behaviour of Akka Actor

我正在学习如何使用 context.become 来控制 actor 的状态,我正在使用此代码:

class MyActor extends Actor {

  override def receive: Receive = {
     println("Happens here")
     active(Set.empty)
   }

  def active(isInSet: Set[String]): Receive = {
    case Add(key) =>
      context.become(active(isInSet+key))
    case Contains(key) =>
      sender() ! isInSet(key)
    case ShowAll =>
      println(isInSet.toSeq)
  }

}

case class Add(key: String)
case class Contains(key: String)
object ShowAll


object DemoBecome extends App{

override def main(args: Array[String]): Unit = {

 val system = ActorSystem("BecomeUnbecome")
 val act = system.actorOf(Props(classOf[MyActor]), "demoActor")

 act ! Add("1")
 act ! ShowAll
 act ! Add("2")
 act ! ShowAll

 Thread.sleep(10000)
 System.exit(0)

}

当我发送第一条消息时,"receive" 工作并打印消息,在第二条消息不显示后,这是我的输出:

Happens here
Set()
Vector(1)
Set(1)
Vector(1, 2)

如果我更改接收方法,为此:

def receive = {
  case a: Add => println("happens here Add" )
  case c: Contains => println("happens here Contains")
  case ShowAll => println("happens here Show")
}

我收到此输出:

happens here Add
happens here Show
happens here Add
happens here Show

所以我尝试跟踪 "receive" 为 "blocked" 的时刻,但我没有成功,我的疑问是:当我在演员中使用 context.become 时, Akka 如何以及何时处理第一条消息之后的消息?

当您使用 context.become 时,您正在改变 actor 的行为。这意味着,当 actor 使用默认 receive 行为启动它时。但是,当它收到一条消息时,它会打印消息 Happens here 并使用部分函数 active 来处理它。

因为在 active 中调用 context.become(active(_)) 演员的行为发生了变化。从现在开始,当消息发送给 actor 时,它将执行部分函数 active 而不是 receive 方法,这就是为什么你不会在输出中多次看到 Happens here .