我正在trait
内对Future
s进行一些操作。
trait MyTrait {
//Future based operations
}
与其为我的Future
使用ExecutionContext.Implicits.global
,我想使用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
}
}
在我的Actor内部,我可以进行查找以获取执行上下文。
implicit val ec = context.system.dispatchers.lookup("akka.my-batch-dispatcher")
现在确定如何在我的特质中做到这一点。
您可以将其添加为特征的抽象隐式值:
trait MyTrait {
implicit val ec: ExecutionContext
//Future based operations
}
然后,实现特征的代码应确保提供 ExecutionContext。如果这是一个Actor,你可以做这样的事情:
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?")
}
}
我没有测试它,但我认为这应该有效。