如何在Play2.4/Scala中自动将参与者订阅到akka事件总线
我开始深入AKKA/活动巴士和相关 我创建了一个小测试参与者,如下所示:如何在Play2.4/Scala中自动将参与者订阅到akka事件总线,scala,playframework,akka,playframework-2.4,Scala,Playframework,Akka,Playframework 2.4,我开始深入AKKA/活动巴士和相关 我创建了一个小测试参与者,如下所示: class TestActor extends Actor with ClassLogger{ @throws[Exception](classOf[Exception]) override def preStart(): Unit = { context.system.eventStream.subscribe(context.self, classOf[FormFieldValue]
class TestActor extends Actor with ClassLogger{
@throws[Exception](classOf[Exception])
override def preStart(): Unit = {
context.system.eventStream.subscribe(context.self, classOf[FormFieldValue])
}
override def receive = {
case (v: FormFieldValue) => logger.info("Value received: " + v.fieldValue)
case _ => logger.info("Something unknown")
}
}
以及尝试从应用程序的另一部分发布事件:
system.eventStream.publish(updatedValue)
一切都像以前一样编译和工作,没有任何记录。基本上,演员没有被叫来
现在,我还尝试创建一个模块来注册所有订户,如下所示:
class EventsRegistry @Inject()(system: ActorSystem) extends AbstractModule {
override def configure(): Unit = {
val testListeener = system.actorOf(Props(classOf[TestActor]))
system.eventStream.subscribe(testListeener, classOf[FormFieldValue])
}
}
并在application.conf中配置了模块:
play.modules.enabled += "events.modules.EventsRegistry"
并从演员身上移除了普雷斯特
现在我得到一个错误:
lay.api.PlayException:没有有效的构造函数[模块]
无法实例化[events.modules.EventsRegistry]
我做错了什么
更新
我实现这一目标的唯一方法是在Global#onStart中设置订阅服务器:
但是不推荐使用GlobalSettings…要使其工作,您需要将注册表和模块解耦
package actors
import akka.actor._
import com.google.inject._
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
case class FormFieldValue(fieldValue: String)
class TestActor extends Actor with ActorLogging {
@throws[Exception](classOf[Exception])
override def preStart(): Unit = {
context.system.eventStream.subscribe(context.self, classOf[FormFieldValue])
super.preStart()
}
@throws[Exception](classOf[Exception])
override def postStop(): Unit = {
context.system.eventStream.unsubscribe(context.self)
super.postStop()
}
override def receive = {
case (v: FormFieldValue) => log.info("Value received: " + v.fieldValue)
case _ => log.info("Something unknown")
}
}
@Singleton
class EventBusLifeCycle @Inject()(system: ActorSystem, lifecycle: ApplicationLifecycle) {
val testListener = system.actorOf(Props(classOf[TestActor]))
lifecycle.addStopHook { () =>
Future.successful(system.stop(testListener))
}
}
class EventBusModule extends AbstractModule {
def configure() = {
bind(classOf[EventBusLifeCycle]).asEagerSingleton()
}
}
并在application.conf中注册该模块
play.modules.enabled += "actors.EventBusModule"
Play无法将ActorSystem注入模块类。这个答案解决了问题。谢谢
play.modules.enabled += "actors.EventBusModule"