首先定义2个消息类
object MyRequest { var message:String=null }
object MyResponse { var message:String=null }
定义2个通信的actor
class Student(teacherRef:ActorRef) extends Actor{ val log=Logging(context.system,this) def receive={ case MyRequest =>{ log.info(MyRequest.message)//teacherRef ! QuoteRequest2 teacherRef ! MyRequest } case MyResponse =>{ log.info(MyResponse.message) } } }
class Teacher extends Actor { val log=Logging(context.system,this) def receive={ case MyRequest =>{ log.info("teacher已经收到信息=="+MyRequest.message)//teacherRef ! QuoteRequest2 MyResponse.message="ok ,i get it" sender ! MyResponse } } }
定义执行的主函数
object MyMain { def main(args: Array[String]): Unit = { val system = ActorSystem("HelloSystem") // default Actor constructor val teacherRef = system.actorOf(Props[Teacher], name = "myteacher") val studentRef = system.actorOf(Props(new Student(teacherRef)), name = "mystudent") MyRequest.message="这是我的邮件 请teacher查收" studentRef ! MyRequest } }
运行结果如下:
[INFO] [10/25/2016 17:24:49.710] [HelloSystem-akka.actor.default-dispatcher-3] [akka://HelloSystem/user/mystudent] 这是我的邮件 请teacher查收 [INFO] [10/25/2016 17:24:49.710] [HelloSystem-akka.actor.default-dispatcher-2] [akka://HelloSystem/user/myteacher] teacher已经收到信息==这是我的邮件 请teacher查收 [INFO] [10/25/2016 17:24:49.710] [HelloSystem-akka.actor.default-dispatcher-2] [akka://HelloSystem/user/mystudent] ok ,i get it