如何从 ActorFlow 获取演员参考 (ActorRef)? [英] How to get an actor reference (ActorRef) from ActorFlow?

查看:83
本文介绍了如何从 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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆