gpt4 book ai didi

scala - Akka Actor - 创建 Actor 池

转载 作者:行者123 更新时间:2023-12-01 12:42:38 24 4
gpt4 key购买 nike

我在 Scala 中创建了以下 Akka Actor 代码。当创建单个 workerActor 时,代码工作正常。但是,当我尝试使用循环逻辑创建一个工作角色池时,代码默默地失败了。知道如何解决这个问题吗?如何获得更多要打印的调试信息?

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)
}
}
}

最佳答案

尝试像这样创建您的池:

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

此外,将其作为 Junit 测试运行时,程序会在子 actors 有机会接收到消息之前终止。我通过在将 HelloWorld 消息发送到 master< 的循环之后添加一个 Thread.sleep(5000) 来验证这一点。然后,我稍微调整了您的代码以使用 akka-testkit 中的 Akka 的 TestActorRef,这将强制所有内容都使用 CallingThreadDispatcher 以在整个测试过程中同步执行,并且一切都按预期进行。我更改的两行是:

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

关于scala - Akka Actor - 创建 Actor 池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22797543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com