为什么 actorSystem 没有使用自定义调度程序将 actor 创建为 运行

Why the actorSystem is not creating the actor to run with custom dispatcher

您好,文件 application-typed.conf 中有以下类型安全配置。

    akka {
      loggers = ["akka.event.slf4j.Slf4jLogger"]
      loglevel = "DEBUG"
      logging-filter = "akka.event.slf4j.Slf4jLoggingFilter"
      actor {
        provider = "local"
      }
    }
    
    custom-thread-pool {
      type = Dispatcher
      executor = "thread-pool-executor"
      thread-pool-executor {
        fixed-pool-size = 40
      }
      throughput = 2
    }

以下是 akka 类型的 actor 代码。

    import akka.actor.typed.{ActorSystem, Behavior, DispatcherSelector, PostStop, Signal}
    import akka.actor.typed.scaladsl.AbstractBehavior
    import akka.actor.typed.scaladsl.ActorContext
    import akka.actor.typed.scaladsl.Behaviors
    import com.typesafe.config.ConfigFactory
    import scala.concurrent.ExecutionContext
    
    trait PrintMessage
    case class PrintMessageAny(x: Any) extends PrintMessage
    
    object PrintMeActor {
      def apply(): Behavior[PrintMessage] =
        Behaviors.setup[PrintMessage](context => new PrintMeActor(context))
    }
    
    class PrintMeActor(context: ActorContext[PrintMessage]) extends AbstractBehavior[PrintMessage](context) {
      val dispatcherSelector: DispatcherSelector = DispatcherSelector.fromConfig("custom-thread-pool")
      implicit val executionContext: ExecutionContext = context.system.dispatchers.lookup(dispatcherSelector)
    
      println(s"PrintMeActor Application started in Thread ${Thread.currentThread().getName}")
    
      override def onMessage(msg: PrintMessage): Behavior[PrintMessage] = {
        // No need to handle any messages
        println(s"Got $msg in Thread ${Thread.currentThread().getName}")
        Behaviors.same
      }
    
      override def onSignal: PartialFunction[Signal, Behavior[PrintMessage]] = {
        case PostStop =>
          context.log.info("PrintMeActor Application stopped")
          this
      }
    }
    
    object TestTypedActorApp extends App {
      val config = ConfigFactory.load("application-typed.conf")
      val as: ActorSystem[PrintMessage] = ActorSystem(PrintMeActor(), "PrintAnyTypeMessage", config)
      as.tell(PrintMessageAny("test"))
      Thread.sleep(2000)
    }

当我 运行 代码时,我得到以下输出。

PrintMeActor Application started in Thread PrintAnyTypeMessage-akka.actor.default-dispatcher-6 Got PrintMessageAny(test) in Thread PrintAnyTypeMessage-akka.actor.default-dispatcher-6

我想让这个演员 运行 在自定义线程池上,但它没有发生。我怎样才能达到同样的效果?

通过传递与所需调度程序相对应的 akka.actor.typed.DispatcherSelector(扩展 akka.actor.typed.Props),将调度程序与 actor 相关联。

在自定义调度程序上生成 ActorSystem 时,只能通过采用 ConfigActorSystemSetup 的重载传递 Props

如果想要覆盖用户监护人角色(具有您传递给 ActorSystem 的行为的角色),则将该调度程序设置为默认调度程序可能更有意义:

 akka.actor.default-dispatcher {
   executor = "thread-pool-executor"

   thread-pool-executor {
     fixed-pool-size = 40
   }
   throughput = 2
 }