我在Scala中创建了以下Akka Actor代码。创建单个workerActor时,代码工作正常。但是当我尝试使用循环逻辑创建一个worker actor池时,代码会无声地失败。知道如何解决这个问题吗?如何获得更多要打印的调试信息?
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 :(得分:3)
尝试创建这样的游戏池:
val workerActors = context.actorOf(Props[WorkerActor].withRouter(RoundRobinPool(5)), name = "WorkerActors")
此外,当将其作为Junit测试运行时,程序将在子actor有机会接收消息之前终止。我通过在将Thread.sleep(5000)
和Hello
消息发送到World
的循环之后添加master
来验证这一点。然后我稍微调整了你的代码,使用来自akka-testkit的Akka&#39; TestActorRef
,它将强制所有内容使用CallingThreadDispatcher在整个测试过程中获得同步执行,一切都按预期工作。我更改的两行是:
implicit val _system = ActorSystem("MainEngineActor")
val master = TestActorRef(new MainEngineActor())