我有一个带有类型化参与者的集群分片应用程序。演员看起来像这样:
object TestActor {
sealed trait Command
final case class Inte(i: Int) extends Command
final case class Stringaki(s: String) extends Command
val TypeKey = EntityTypeKey[Command]("Test")
def defaultThreadBehavior(id: String): Behavior[Command] = Behaviors.setup { ctx =>
Behaviors.receiveMessage { cmd =>
cmd match {
case Inte(i) =>
ctx.log.info(System.currentTimeMillis()/1000 + " Received int: " + i)
Thread.sleep(1000)
case Stringaki(s) =>
ctx.log.info(System.currentTimeMillis()/1000 + " Received string: " + s)
Thread.sleep(1000)
}
Behaviors.same
}
}
}
演员是通过分片信封创建的,如下所示:
val system_config = ConfigFactory.parseString(
"""
|akka {
| actor {
| provider = "cluster"
| prio-dispatcher {
| type = "Dispatcher"
| mailbox-type = "PriorityMailbox"
| }
| }
| remote {
| netty.tcp {
| hostname = "127.0.0.1"
| port = 2551
| }
| }
| cluster {
| seed-nodes = [
| "akka.tcp://TestApp@127.0.0.1:2551"
| ]
| sharding {
| number-of-shards = 10
| use-dispatcher = "akka.actor.prio-dispatcher"
| }
| }
|}
|""".stripMargin)
val system = ActorSystem(Behaviors.empty[TestActor.Command], "TestApp",system_config)
val sharding = ClusterSharding(system)
val shardRegion = sharding.init(Entity(TestActor.TypeKey, ctx => defaultThreadBehavior(ctx.entityId)))
(0 to 9).foreach{
i =>
shardRegion ! ShardingEnvelope(0.toString, Inte(i))
}
(0 to 9).foreach{
i =>
shardRegion ! ShardingEnvelope(0.toString, Stringaki(i.toString))
}
两个for循环将消息发送到同一actor。第一个循环发送整数,第二个循环发送字符串。当参与者处理消息时,它会休眠以在队列中建立消息并测试优先级。优先级邮箱是在系统配置中配置的,UnboundedPriorityMailbox实现如下:
class PriorityMailbox (settings: Settings, cfg: Config) extends UnboundedPriorityMailbox(
PriorityGenerator {
case Stringaki => 0
case _ => 1
}
)
为什么Actor按消息到达的顺序打印消息,而没有考虑优先级生成器?
答案 0 :(得分:0)
为什么您没有看到优先邮箱的简短答案是您的TestActor
不是使用优先邮箱,而是默认邮箱。仅Akka群集分片系统正在使用优先级邮箱。 akka.cluster.sharding.use-dispatcher
的{{3}}描述:
# The id of the dispatcher to use for ClusterSharding actors.
# If specified you need to define the settings of the actual dispatcher.
# This dispatcher for the entity actors is defined by the user provided
# Props, i.e. this dispatcher is not used for the entity actors.
确实,您发送的每条消息都通过优先级邮箱,但是由于群集分片内部的参与者没有处于休眠状态,因此没有积压的情况(尽管在某些情况下,尤其是内核较少的情况下,可以优先处理的待办事项列表。
要让实体参与者在具有优先级邮箱的调度程序中运行,您将拥有类似的东西
val entityDispatcherProps = DispatcherSelector.fromConfig("akka.actor.prio-dispatcher")
val baseEntity = Entity(TestActor.TypeKey)(ctx => defaultThreadBehavior(ctx.entityId))
val shardRegion = sharding.init(baseEntity.withEntityProps(entityDispatcherProps))