我想使用Akka创建一个应用程序,其中不同的actor将使用相同的路由器来提交他们的工作。
我的问题是,是否可以将来自不同演员的类似作业发送到Akka中的同一路由器?
答案 0 :(得分:0)
只要你的演员处于同一个ActorSystem
,那么你应该没有问题。
在这种情况下,接收消息的actor将具有不同的sender
。
请注意,这听起来像是一个糟糕的设计。尽管如此,这里有一个例子:
import akka.actor.{ActorSystem, ActorRef, Props, Actor}
import akka.routing.RoundRobinPool
class Worker extends Actor {
override def receive: Receive = {
case PowerMessage(value) =>
sender ! ResultMessage(value * value)
}
}
class Sender(router: ActorRef) extends Actor {
val actorName = self.path.name
override def receive: Actor.Receive = {
case m @ PowerMessage(value) =>
router ! m
case ResultMessage(value) =>
System.out.println(s"Sender ($actorName). Result: $value.")
}
}
class Master(workers: Int) extends Actor {
val router: ActorRef = context.actorOf(
Props[Worker].withRouter(RoundRobinPool(workers)),
name = "workerRouter"
)
val sender1 = context.actorOf(
Props(new Sender(router)),
name = "sender1"
)
val sender2 = context.actorOf(
Props(new Sender(router)),
name = "sender2"
)
override def receive: Actor.Receive = {
case StartCalc =>
(1 to workers * 2).foreach {
case index =>
if (index % 2 == 1) {
sender1 ! PowerMessage(index)
} else {
sender2 ! PowerMessage(index)
}
}
}
}
object Senders {
def main(args: Array[String]): Unit = {
val system = ActorSystem("TestSystem")
val master = system.actorOf(
Props(new Master(10)),
name = "master"
)
master ! StartCalc
}
}
sealed trait MainMessage
case class PowerMessage(value: Long) extends MainMessage
case class ResultMessage(value: Long) extends MainMessage
case object StartCalc extends MainMessage