2014-04-01 231 views
2

我在Scala中創建了以下Akka演員代碼。代碼工作正常,當一個workerActor創建。但是,當我嘗試使用循環法邏輯創建一個工作者角色池時,代碼默默失敗。任何想法如何解決這個問題?我如何獲得更多的打印調試信息?Akka演員 - 創建演員羣

import scala.collection.immutable.Map 
import scala.collection.mutable.ArrayBuffer 

import akka.actor.actorRef2Scala 
import akka.actor.ActorSystem 
import akka.actor.Props 
import scala.concurrent.Await 
import scala.concurrent.duration._ 
import akka.pattern.ask 
import akka.util.Timeout 
import akka.actor._ 
import org.junit._ 
import org.junit.Assert._ 
import messaging.actors._ 
import akka.routing.RoundRobinRouter 
import akka.routing._ 

class MainEngineActorTest { 

    @Test 
    def testMainActor() = { 
    val _system = ActorSystem("MainEngineActor") 
    val master = _system.actorOf(Props[MainEngineActor], name = "EngineActor") 

    println ("Created Main Engine Actor") 


    implicit val timeout = Timeout(5 seconds) 

    val userID = new UserID ("test1") 

    println ("Sending messages") 

    for (i <- (1 to 10)) { 
     master ! "Hello" 
     master ! "World" 
    } 

    } 
} 

class MainEngineActor extends Actor with ActorLogging{ 

    // works if we create only a single workerActor 
    //val workerActors = context.actorOf(Props[WorkerActor], name = "WorkerActors") 

    // Doesn't work when we create a pool of worker actors - how do we fix this? 
    // why doesn't this work and why aren't any error messages printed? 
    val workerActors = context.actorOf(RoundRobinPool(5).props(Props[WorkerActor]), name = "WorkerActors") 

    def receive: Receive = {  
    case request => {  
     workerActors forward request 
    }  
    } 
} 

class WorkerActor extends Actor { 

    def receive: Receive = {    
    case request => { 
     println ("RequestReceived =" + request) 
    } 
    } 
} 
+0

「沉默地失敗」是什麼意思?你有輸出嗎? – Ryan

+0

我期待演員打印出:「RequestReceived = World RequestReceived = Hello」,但演員不打印任何東西。然而,如果我只是創建一個演員(而不是一羣演員),一切正常。 – user3482479

+0

如果您發佈您正在使用的akka​​版本,路由器初始化語法隨Akka 2.3更改將會有所幫助 – pushy

回答

2

嘗試創建池這樣,而不是:

val workerActors = context.actorOf(Props[WorkerActor].withRouter(RoundRobinPool(5)), name = "WorkerActors") 

此外,運行此作爲JUnit測試時,該程序前兒童演員有機會收到消息終止。我通過在發送HelloWorld消息到master的循環之後添加Thread.sleep(5000)來驗證此情況。然後,我稍微調整了一下代碼,以便使用akka-testkit中的Akka's TestActorRef,這將迫使所有人使用CallingThreadDispatcher在整個測試中獲得同步執行,並且所有內容都按預期工作。我改變的兩條線是:

implicit val _system = ActorSystem("MainEngineActor") 
val master = TestActorRef(new MainEngineActor())