1. 程式人生 > >基於Actor模型的AkkaDemo

基於Actor模型的AkkaDemo

什麼是Akka、什麼是Actor請自行百度,這裡一個Demo程式碼玩一下Akka裡的Actor訊息傳遞。

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

/**
  *AkkaActor
  *自己執行來玩玩,理解中間的邏輯順序
  */
object Demo extends App{

  val as = ActorSystem("aaaa")
  val mas = as.actorOf(Props[MyActorShow])
  val masa = as.actorOf(Props[MyActorShowA])
  mas!("凱總",masa)

}

class MyActorShow extends Actor{
  override def receive: Receive = {
    case x:String =>{
      println(s"1收到來自MyActorShowA的訊息:$x")
      println("2MyActorShow傳送了:")
      val msg = Console.readLine()
      sender!msg
    }
    case (x:String,y:ActorRef) => {println(s"3傳送了$x");y!x}
  }
}

class MyActorShowA extends Actor{
  override def receive: Receive = {
    case x:String => {
      println(s"4收到了來自MyActorShow的訊息:$x")
      println("5MyActorShowA說:")
      val msg = Console.readLine()
      sender!msg
    }
  }
}