2013-12-17 57 views
1

處理參與者模型中的多條消息的最佳方法是哪種?在akka中處理多條消息

例如,如果您需要來自演員的2個不同的消息返回,如何訪問和檢索來自另一個演員的消息?

回答

1

在阿卡的演員可以到許多不同類型的消息作出迴應,併發送任何消息,以及...

case class Message1(id: Long) 
case class Message2(thing: String) 
case class Response1(x: Int) 
case class Response2(y: Int) 

class MyActor extends Actor with ActorLogging { 

    def receive = { 
     case Message1(id) => sender ! Response1(id) 
     case Message2(t) => sender ! Response2(1) 
    } 
} 

所有你需要做的是尋找他們的receive方法case語句。

1

下面是一個示例,顯示如何處理演員的不同結果。

鑑於以下演員:

case object GiveMeAFruit 

trait Fruit 

case class Apple(size: Int) extends Fruit 

case class Pear(color: String) extends Fruit 

class FruitNinja extends Actor { 
    def receive = { 
    case GiveMeAFruit => 
     if (math.random > 0.5) 
     sender ! Apple(42) 
     else 
     sender ! Pear("yellow") 
    } 
} 

從另一個演員

class HungryActor extends Actor { 
    val fruitNinja = context.actorOf(Props[FruitNinja]) 

    override def preStart = { 
    context.system.scheduler.schedule(5 seconds, 5 seconds, fruitNinja, GiveMeAFruit) 
    } 

    def receive = { 
    // handle different returns from FruitNinja 
    case Apple(size) => 
     println(s"Got an apple sized $size.") 
    case Pear(color) => 
     println(s"Got a $color pear") 
    } 
} 

從 '正常' 代碼

import akka.pattern.ask 

def eatSomething = { 
    // create an instance of the actor using an actorsystem in scope 
    val fruitNinja = Akka.system.actorOf(Props[FruitNinja]) 

    (fruitNinja ? GiveMeAFruit).mapTo[Fruit].map{ 
    // handle different returns from FruitNinja 
    case Apple(size) => 
     println(s"Got an apple sized $size.") 
    case Pear(color) => 
     println(s"Got a $color pear") 
    } 
} 
+0

丹科演員相通 - 是有幫助 –