Akka Actor转发消息示例

你可以将消息从一个演员转发给另一个演员。在这种情况下, 即使消息正在通过”调解者”, 也将维护Actor的地址/引用。

在编写充当路由器, 负载平衡器, 复制器等的角色时很有用。


Akka演员转发消息示例

import akka.actor.{Actor, ActorSystem, Props};

class ActorExample extends Actor{
  def receive = {
    case message:String => println("Message received from "+sender().path.name+" : "+message);
    val child = context.actorOf(Props[Actor2], "ChildActor");
    println("message forwarded to child Actor");  
    child ! message ;    // Message forwarded to child actor 

    case _ => println("Unknown message");
  }
}

class Actor2 extends Actor{
  def receive ={
    case message:String => println("Message received from "+sender().path.name+" : "+message);
    case _ => println("Unknown message");
  }
}


object ActorExample{
  def main(args:Array[String]){
    val actorSystem = ActorSystem("ActorSystem");
    val actor = actorSystem.actorOf(Props[ActorExample], "RootActor");
    actor ! "Hello"
  }
}

输出

Message received from deadLetters : Hello
message forwarded to child Actor
Message received from RootActor : Hello
微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?