2013-12-17 55 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

丹科演员相通 - 是有帮助 –