我有未知数量的工作要由已知(当然)数量的 Actor 执行。 Actor 完成工作后,初始工作数量可能会增加。也就是说,一个参与者在完成其任务后,可能会添加一个要执行的新作业。
我处理这个问题的方法是让每个 actor 在完成其工作后向 master 发送一条消息,不仅包含执行结果,还带有一个“标志”,表明该 actor 现在处于空闲状态。 master 有一个作业队列和一个空闲 actor 队列,每当一个 actor 发送“作业完成消息”时,master 就会检查该 actor 是否还有其他事情要做......等等,直到作业队列是空的,闲置队列已满...那时我关闭了系统。这里没有太多的监督,所以我觉得我做的不对...
我没有使用路由器,因为我找不到查询路由器空闲角色的方法,所以我的问题是:
在 Akka 中处理上述情况的“正确”方法是什么?
最佳答案
你应该看看Akka's routing capabilites. SmallestMailboxRouter
可能正是您正在寻找的。p>
作为替代方案,您可以按需创建 Actor ,即对于每个任务,都会动态创建一个新 Actor 。中央 Actor 跟踪所有当前活跃的 Actor 。一旦 worker actor 完成,它会向自己发送一个 PoisonPill
。并通知主人它的关闭(主动,或通过 Akka 将发送给监督 Actor 的标准 Terminate
消息)。一旦没有更多的 Activity 参与者,即没有更多的任务,控制者参与者就会关闭系统。
看完评论补充:
查看 SmallestMailboxLike
的来源,由 SmallestMailboxRouter
混合的 Scala 特性.警告:您应该具备 Scala 的基本知识。但如果你想使用 Akka,这通常是一个好主意......方法 isProcessingMessage(ActorRef)
可以理解为isNotIdle(ActorRef)
// Returns true if the actor is currently processing a message.
// It will always return false for remote actors.
// Method is exposed to subclasses to be able to implement custom
// routers based on mailbox and actor internal state.
protected def isProcessingMessage(a: ActorRef): Boolean = a match {
case x: LocalActorRef ?
val cell = x.underlying
cell.mailbox.isScheduled && cell.currentMessage != null
case _ ? false
}
// Returns true if the actor currently has any pending messages
// in the mailbox, i.e. the mailbox is not empty.
// It will always return false for remote actors.
// Method is exposed to subclasses to be able to implement custom
// routers based on mailbox and actor internal state.
protected def hasMessages(a: ActorRef): Boolean = a match {
case x: LocalActorRef ? x.underlying.mailbox.hasMessages
case _ ? false
}
关于java - 如何知道 Actor 是否空闲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11377346/