简体   繁体   中英

Accessing a custom dispatcher defined in application.conf inside a Scala trait

I'm doing a few operations on Future s inside an trait .

trait MyTrait {
  //Future based operations 

}

Instead of using ExecutionContext.Implicits.global for my Future , I want to use one that is defined in my application.conf .

akka {
  my-batch-dispatcher {
    type = Dispatcher
    executor = "fork-join-executor"
    fork-join-executor {
      parallelism-min = 10
      parallelism-factor = 2.0
      parallelism-max = 10
    }
    throughput = 20
  }
}

Inside my actor I can do a lookup to get the execution context.

  implicit val ec = context.system.dispatchers.lookup("akka.my-batch-dispatcher")

Now sure how to do this inside my trait.

You can add it as abstract implicit value of the trait:

trait MyTrait {
  implicit val ec: ExecutionContext
  //Future based operations 

}

Then the code the implement the trait should make sure to provide the ExecutionContext. If that is an Actor you may do something like:

class MyActor extends Actor with MyTrait {
  implicit val ec = context.system.dispatchers.lookup("akka.my-batch-dispatcher")
  def receive = {
    case "hello" => println("hello back at you")
    case _       => println("huh?")
  }
}

I didn't test it but I think this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM