0

嗨,文件中有以下类型安全配置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 应用程序在线程中启动 PrintAnyTypeMessage-akka.actor.default-dispatcher-6 在线程中得到 PrintMessageAny(test) PrintAnyTypeMessage-akka.actor.default-dispatcher-6

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

4

1 回答 1

0

当您生成它时,您可以通过传递与所需调度程序相对应的akka.actor.typed.DispatcherSelector(扩展)来将调度程序与演员相关联。akka.actor.typed.Props

ActorSystem自定义调度程序上生成 时,只能通过Props采用 aConfig或a 的重载ActorSystemSetup

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

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

   thread-pool-executor {
     fixed-pool-size = 40
   }
   throughput = 2
 }
于 2021-05-06T23:04:08.390 回答