你可以将消息从一个演员转发给另一个演员。在这种情况下, 即使消息正在通过”
调解者”
, 也将维护Actor的地址/引用。
【Akka 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
推荐阅读
- Akka Actor介绍和用法详解
- Scala特性混合用法示例
- Scala字符串介绍和用法示例
- Scala特质介绍和用法示例
- Scala多维数组
- Scala final关键字用法示例
- Scala数组介绍和用法
- Scala访问修饰符用法实例
- Spring Boot -- 启动流程分析之ApplicationContext 中