Akka在运行时对消息进行实时切换处理的特性: become和unbecome

Akka支持Actor消息循环处理部分的热切换,调用context.become方法可以使用新的消息循环处理替换当前的消息处理器,被替换的消息处理器被压到一个栈结构,支持消息处理器的出栈和入栈。
注:但Actor重启时,它的消息循环处理恢复到初始的行为。

实例:Actor运行期间对消息进行交替处理

package myakka.example


import akka.actor.{Actor, ActorSystem, Props}
/**
 * Created by jsz on 2016/1/17.
 */

case class Scala()
case class Spark()


class SparkFlinkActor extends Actor {
  import context._;
  var count = 0;


  override def receive: Receive = {
    case Spark =>
      println(count + ": Welcome to Spark!!!")
      count = count + 1
      Thread.sleep(500)
      self ! Scala
      become {
        case Scala =>
          println(count + ": Welcome to Scala!!!")
          count = count + 1
          Thread.sleep(500)
          self ! Spark
          unbecome()
      }

      if (count > 10)
        context.stop(self)
  }
}

object SparkFlinkDemo {
  def main(args: Array[String]) {
    val _system = ActorSystem("SparkScala")
    val master = _system.actorOf(Props[SparkFlinkActor],"master")

    master ! Spark

    Thread.sleep(8000)
    _system.shutdown()
  }
}




你可能感兴趣的:(Akka在运行时对消息进行实时切换处理的特性: become和unbecome)