actor 模型原理 (三)

上面这个图呢,展示了老师这个actor收到消息之后,给学生回复的过程

DriverApp 发送一个初始化 InitSignal 消息给 StudentActor


 StudentActor 收到这个消息之后给老师发了一个 QuoteRequest


老师 回复了一个 QuoteResponse.学生收到之后再把这个回复打印出来


对于驱动程序,那么上面它做的事情用代码就是这样来做


 //Initialize the ActorSystem
  val system = ActorSystem("UniversityMessageSystem")

  //construct the teacher actor
  val teacherRef = system.actorOf(Props[TeacherActor], "teacherActor")

  //construct the Student Actor - pass the teacher actorref as a constructor parameter to StudentActor
  val studentRef = system.actorOf(Props(new StudentActor(teacherRef)), "studentActor")

  //send a message to the Student Actor
  studentRef ! InitSignal

按照我们的理解,就是直接创建一个学生actor的代理,然后发送消息给这个代理,但是学生actor的代理,需要老师actor的代理作为构造参数放进去,这种就是驱动模式


即我让某个actor发送某个请求给xxx, 比如你是学生家长,你要让你的孩子给老师打个电话,你丫的是不是得告诉学生老师的电话啊。


那么对于学生这个actor来说,它也是actor,收到的消息也是前面mailbox那一套机制,那么当它收到这个initsignal的时候,你需要在receive里面把要做的事情定义清楚


def receive = {  
    case InitSignal=> {
          teacherActorRef!QuoteRequest
    }
    ...
    ...

很简单,就是这样的代码


case QuoteResponse(quoteString) => {  
      log.info ("Received QuoteResponse from Teacher")
      log.info(s"Printing from Student Actor $quoteString")
}

接收到的消息打印一下,也是放在receive方法里面


class TeacherActor extends Actor with ActorLogging {

  val quotes = List(
    "Moderation is for cowards",
    "Anything worth doing is worth overdoing",
    "The trouble is you think you have time",
    "You never gonna know if you never even try")

  def receive = {

    case QuoteRequest => {

      import util.Random

      //Get a random Quote from the list and construct a response
      val quoteResponse = QuoteResponse(quotes(Random.nextInt(quotes.size)))

      //respond back to the Student who is the original sender of QuoteRequest
      sender ! quoteResponse

    }
  }
}

那么老师要回复消息怎么回复呢,使用sender,sender应该是Actor内置的一个成员,直接调用就可以了







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值