vpt*_*ron 3 scala akka akka-io
使用 Akka-IO TCP,在 Actor 中建立连接的过程如下:
class MyActor(remote: InetSocketAddress) extends Actor {
IO(Tcp) ! Connect(remote) //this is the first step, remote is the address to connect to
def receive = {
case CommandFailed(_: Connect) => context stop self // failed to connect
case Connected(remote, local) =>
val connection = sender()
connection ! Register(self)
// do cool things...
}
}
Run Code Online (Sandbox Code Playgroud)
您Connect向 发送消息IO(Tcp)并期望收到CommandFailed或Connected消息。
现在,我的目标是创建一个包装 TCP 连接的 actor,但我希望我的 actor 仅在建立连接后才开始接受消息 - 否则,在等待消息时,Connected它将开始接受查询,但没有人可以发送他们到。
我尝试过的:
class MyActor(address: InetSocketAddress) extends Actor {
def receive = {
case Initialize =>
IO(Tcp) ! Connect(address)
context.become(waitForConnection(sender()))
case other => sender ! Status.Failure(new Exception(s"Connection to $address not established yet."))
}
private def waitForConnection(initializer: ActorRef): Receive = {
case Connected(_, _) =>
val connection = sender()
connection ! Register(self)
initializer ! Status.Success(Unit)
// do cool things
case CommandFailed(_: Connect) =>
initializer ! Status.Failure(new Exception("Failed to connect to " + host))
context stop self
}
}
Run Code Online (Sandbox Code Playgroud)
我的第一个receive期望是一条虚构的Initialize消息,它将触发整个连接过程,一旦完成,发送者Initialize就会收到一条成功消息,并知道它可以开始发送查询。
我对此不太满意,它迫使我创造我的演员
val actor = system.actorOf(MyActor.props(remote))
Await.ready(actor ? Initialize, timeout)
Run Code Online (Sandbox Code Playgroud)
而且它不会很“重启”友好。
有什么想法可以保证我的参与者在 Tcp 层回复之前不会开始从邮箱接收消息吗Connected?
| 归档时间: |
|
| 查看次数: |
802 次 |
| 最近记录: |