[英]inject akka actors using guice in play 2.5
在Play 2.2中,我创建了GlobalActorProducer类
import akka.actor.{Props, IndirectActorProducer, Actor}
import play.api.Play
class GlobalActorProducer[T <: Actor](val aClass: Class[T]) extends IndirectActorProducer {
def produce(): T = Play.current.global.getControllerInstance(aClass)
def actorClass: Class[T] = aClass
}
object GlobalActorProducer {
def apply[T <: Actor](targetClass: Class[T]): Props = Props.create(classOf[GlobalActorProducer[T]], targetClass)
}
我想将播放框架升级到2.5。 Play.current在播放2.5中已弃用,因此我通过使用Injector修改了此类,但注射器始终为Null。 我需要如何使此类在Play 2.5上正常工作?
import akka.actor.{Props, IndirectActorProducer, Actor}
import javax.inject.Inject
import com.google.inject.Injector
class GlobalActorProducer[T <: Actor](val aClass: Class[T]) extends IndirectActorProducer {
@Inject private var injector : Injector = _
def produce(): T = injector.getInstance(aClass)
def actorClass: Class[T] = aClass
}
object GlobalActorProducer {
def apply[T <: Actor](targetClass: Class[T]): Props = Props.create(classOf[GlobalActorProducer[T]], targetClass)
}
注入Actor
是一个坏习惯。 ActorRef是由actor系统以特殊方式创建的,无需公开实际对象而是公开ActorRef(句柄)。
解:
这个想法是注入ActorSystem
,然后使用
actorSystem.actorOf
您希望利用Play在play.api.libs.concurrent.AkkaGuiceSupport命名空间中提供的Akka Guice支持,如Dependency Injecting Actors中所述 。
Play提供了一些帮助者来帮助提供演员绑定。 这些允许actor自身进行依赖注入,并允许actor的actor ref注入其他组件。 要使用这些助手来绑定角色,请按照依赖关系注入文档中的描述创建一个模块,然后混合使用AkkaGuiceSupport特性,并使用bindActor方法绑定角色:
import com.google.inject.AbstractModule
import play.api.libs.concurrent.AkkaGuiceSupport
import actors.ConfiguredActor
class MyModule extends AbstractModule with AkkaGuiceSupport {
def configure = {
bindActor[ConfiguredActor]("configured-actor")
}
}
@Singleton
class Application @Inject() (@Named("configured-actor") configuredActor: ActorRef, components: ControllerComponents)
(implicit ec: ExecutionContext) extends AbstractController(components) {
implicit val timeout: Timeout = 5.seconds
def getConfig = Action.async {
(configuredActor ? GetConfig).mapTo[String].map { message =>
Ok(message)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.