如何从 ActorFlow 获取演员参考 (ActorRef)?

编程入门 行业动态 更新时间:2024-10-12 01:27:57
本文介绍了如何从 ActorFlow 获取演员参考 (ActorRef)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

根据 在 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)?

本文发布于:2023-11-25 02:32:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627971.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:演员   ActorFlow   ActorRef

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!