如何从ActorFlow获取actor引用(ActorRef)?

时间:2017-03-21 09:57:33

标签: scala playframework playframework-2.0 akka

根据Play documentation on WebSockets,建立WebSocket的标准方法是使用ActorFlow.actorRef,它使用一个函数返回我的actor的Props。我的目标是获取对这个底层ActorRef的引用,例如为了发送第一条消息或将ActorRef传递给另一个actor的构造函数。

就文档中的最小示例而言,我正在努力实现这一目标:

class WebSocketController @Inject() (implicit system: ActorSystem, materializer: Materializer) {

  def socket = WebSocket.accept[String, String] { request =>
    val flow = ActorFlow.actorRef { out => MyWebSocketActor.props(out) }
    // How to get the ActorRef that is created by MyWebSocketActor.props(out)?
    // Fictitious syntax (does not work)
    flow.underlyingActor ! "first message send"
    flow
  }
}

如何获取对创建的actor的引用?

如果此时无法获得ActorRef(它是否需要实现流程的实现?),那么存储对创建的actor的引用的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

使用Actor.preStart()钩子,你可以做一些技巧来访问actorRef

class MyWebSocketActor(
  out: ActorRef, 
  firstMessage: Any, 
  actorRegistry: ActorRef
) extends Actor {
  import play.api.libs.json.JsValue
  override def preStart(): Unit = {
    self ! firstMessage
    actorRegistry ! self
  }
  ...
}

def socket = WebSocket.accept[String, String] { request =>
  ActorFlow.actorRef { out => 
    Props(new MyWebSocketActor(out, "First Message", someRegistryActorRef)) 
  }
}