使用阿卡期货和演员的并行列表

问题描述:

我要发送的邮件列表,以一个演员,立即收到回复在未来,然后等待所有期货返回到调用方法之前完成。从阅读阿卡文档,我相信Future.sequence是要走的路,但我一直没能得到下面的代码才能正常工作。我得到这个错误从编译器:使用阿卡期货和演员的并行列表

found : akka.dispatch.ActorCompletableFuture 
    required: akka.dispatch.Future[Integer] 
Error occurred in an application involving default arguments. 
      futures += secondary ? GetRandom 
           ^

我敢肯定,我失去了一些东西很明显,但下面的代码似乎是每个实例和API文档“正确的”。

import java.util.Random 
import akka.dispatch.Future 
import akka.actor._ 
import Commands._ 
import collection.mutable.ListBuffer 

object Commands { 
    trait Command 

    case class GetRandom() extends Command 
    case class GenRandomList() extends Command 
} 

class Secondary() extends Actor { 
    val randomGenerator = new Random() 

    override def receive = { 
     case GetRandom() => 
      self reply randomGenerator.nextInt(100) 
    } 
} 

class Primary() extends Actor { 
    private val secondary = Actor.actorOf[Secondary] 

    override def receive = { 

     case GenRandomList() => 

      val futures = new ListBuffer[Future[Integer]] 

      for (i <- 0 until 10) { 
       futures += secondary ? GetRandom 
      } 

      val futureWithList = Future.sequence(futures) 

      futureWithList.map { foo => 
       println("Shouldn't foo be an integer now? " + foo) 
      }.get 
    } 

    override def preStart() = { 
     secondary.start() 
    } 
} 

class Starter extends App { 
    println("Starting") 
    var master = Actor.actorOf(new Primary()).start() 
    master ! GenRandomList() 
} 

什么是发送一系列的消息给一个演员的正确方法,收到的未来,并返回一旦所有的期货已经完成(可以存储从每个将来的结果列表并返回它)。

+0

哪个版本阿卡您使用的是:D与搭配呢? –

+0

阿卡1.2使用Scala 2.9.1。 –

(secondary ? GetRandom).mapTo[Int] 

阿卡?返回Future[Any]但你需要一个Future[Int]

因此,你可以定义哪些接受各类期货品种列表:

val futures = new ListBuffer[Future[Any]] 

或尽快把结果作为Int,因为它是可用的:BTW

for (i <- 0 until 10) { 
    futures += (secondary ? GetRandom) map { 
    _.asInstanceOf[Int] 
    } 
} 

,使它的工作,你需要改变GetRandom的定义:

case object GetRandom extends Command 

an

case GetRandom => 
+0

伟大的回答,感谢您的帮助。我希望我能将两个答案标记为已接受的答案。 –

+1

我建议:Vector.fill(10)(?(二次GetRandom).mapTo [INT]) –

+0

谢谢,我对你的回答发现'mapTo'。它在哪个版本中引入? – paradigmatic