问题
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
}
}
How can I get a reference to the actor that is created?
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?
回答1:
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))
}
}
来源:https://stackoverflow.com/questions/42923671/how-to-get-an-actor-reference-actorref-from-actorflow