根据 在 WebSockets 上播放文档 建立 WebSocket 的标准方法是使用 ActorFlow.actorRef,它接受一个函数返回我的演员的 Props.我的目标是获得对这个底层 ActorRef 的引用,例如为了发送第一条消息或将 ActorRef 传递给另一个演员的构造函数.
According to the Play documentation on WebSockets the standard way to establish a WebSocket is to use ActorFlow.actorRef, which takes a function returning the Props of my actor. My goal is to get a reference to this underlying ActorRef, for instance in order to send a first message or to pass the ActorRef to another actor's constructor.
就文档中的最小示例而言,我正在努力实现这一目标:
In terms of the minimal example from the documentation, I'm trying to achieve this:
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 的引用?
How can I get a reference to the actor that is created?
如果此时无法获得 ActorRef(是否需要实现流程?),存储对创建的 actor 的引用的最简单方法是什么?>
If it is not possible to get an ActorRef at this point (does it require materialization of the flow?), what would be the easiest way to store a reference to the created actor?
推荐答案使用 Actor.preStart() 钩子你可以做一些技巧来访问 actorRef:
Using Actor.preStart() hook you can do some tricks to access the 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)) } }更多推荐
如何从 ActorFlow 获取演员参考 (ActorRef)?
发布评论