如何在Play2.4 / Scala中自动订阅演员到akka事件总线

时间:2016-01-28 22:25:19

标签: scala playframework akka playframework-2.4

我开始潜入AKKA / Event Bus及相关......

我按如下方式创建了一个小测试演员:

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"

并从Actor中删除了preStart。

现在我收到了一个错误:

  

lay.api.PlayException:没有有效的构造函数[Module   [events.modules.EventsRegistry]无法实例化。]

我做错了什么?

更新 我开展工作的唯一方法是在Global#onStart中设置订阅者:

override def onStart(app: play.api.Application) {

        val testListeener = Akka.system.actorOf(Props(classOf[TestActor]))

        Akka.system.eventStream.subscribe(testListeener, classOf[FormFieldValue])

    }

但不推荐使用GlobalSettings ....

1 个答案:

答案 0 :(得分:2)

要使其正常工作,您需要将注册表和模块分离。

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"