akka actor 的request-response简单实现

注:本文章是看blog后的一个阶段小结,只作为个人笔记, 原文链接:http://www.iteblog.com/archives/1154

官网地址贴上:http://doc.akka.io/docs/akka/snapshot/scala/actors.html 

在上篇文章中,我们写明了向actor发送消息的原理,而actor接收到消息后,能够作出response,这个回应可以是发送给发送消息的actor,也可以是别的actor,这里将讨论前者,场景描述如下:

 上图传达了我们此刻想表达的意思。为了简单,我没有在图中画出ActorSystem、Dispatcher 和Mailboxes。

  1、DriverApp个StudentActor发送了一个InitSignal消息;
  2、StudentActor对InitSignal消息作出反应,并且发送了QuoteRequest 消息给TeacherActor;
  3、TeacherActor用QuoteResponse作出了响应;

  4、StudentActor仅仅将QuoteResponse 作为日志打印到控制台/logger。

第一步:由DriverApp 发起,代码如下:

//Initialize the ActorSystem

val system = ActorSystem("UniversityMessageSystem")

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

//create the Student Actor - 
//用TeacherActor 作为StudentActor构造参数,并传入到ActorRef 中,这样StudentActor 将可以用ActorRef发送消息到TeacherActor
val studentRef = system.actorOf(Props(new StudentActor(teacherRef)), "studentActor")

//send InitSignalto student actor
studentRef ! InitSignal

 第二步:StudentActor 接收来自 DriverApp 的 InitSignal 消息,然后给TeacherActor发送一个QuoteRequest

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

    ...

第三步:TeacherActor 对 StudentActor 作出响应 

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
    }
  }
}

 第四步:StudentActor仅仅将QuoteResponse 作为日志打印到控制台/logger

class StudentActor (teacherActorRef:ActorRef) extends Actor with ActorLogging {
  def receive = {
    case InitSignal=> {
      teacherActorRef!QuoteRequest
    }
    case QuoteResponse(quoteString) => {
      log.info ("Received QuoteResponse from Teacher")
      log.info(s"Printing from Student Actor $quoteString")
    }
  }
}
原文地址:https://www.cnblogs.com/key1309/p/5354880.html