akka简单入门例子

阅读更多
spark版本里面用到的就是akka通信,2.0版本 已经不再使用akka了。这里写了一个简单的akka程序。
首先定义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

你可能感兴趣的:(spark,akka)