处理akka中的多条消息

时间:2013-12-17 20:53:32

标签: scala akka actor

在actor模型中处理多条消息的最佳方法是什么?

例如,如果您需要来自演员的两个不同的消息返回,那么如何访问和检索来自另一个演员的两个消息呢?

2 个答案:

答案 0 :(得分:1)

Akka中的演员可以回复许多不同类型的消息,并发送任何消息......

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 :(得分: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")
  }
}