如何在Akka-stream Tcp服务器中关闭连接?

时间:2015-07-29 16:31:33

标签: scala akka akka-stream

我们基于akka-stream的Tcp服务器中close()的预期行为是客户端应该立即看到SocketException,并且在异常之后发布的消息都不应该传递给服务器。但是,必须传递在异常之前发送的最后一条消息。所有新客户端都应该遇到ConnectException。

无法解读关于"关闭连接的段落"在akka-streams 1.0 docs上,我们正在使用Tcp服务器的实现close():

  val serverSource: Promise[ByteString] = Promise[ByteString]()

  var serverBindingOption: Option[Tcp.ServerBinding] = None

  def bind(address: String, port: Int, target: ActorRef, maxInFlight: Int)
    (implicit system: ActorSystem, actorMaterializer: ActorMaterializer): Future[SyslogStreamServer] = {
    implicit val executionContext = system.dispatcher
    val sink = Sink.foreach {
      conn: Tcp.IncomingConnection =>
        val targetSubscriber = ActorSubscriber[Message](system.actorOf(Props(new TargetSubscriber(target, maxInFlight))))

        val targetSink = Flow[ByteString]
          .via(Framing.delimiter(ByteString("\n"), maximumFrameLength = MaxFrameLength, allowTruncation = true))
          .map(raw ⇒ Message(raw))
          .to(Sink(targetSubscriber))

        conn.flow.to(targetSink).runWith(Source(serverSource.future).drop(1)) // drop the last one for no response
    }

    for {
      serverBinding ← Tcp().bind(address, port).to(sink).run()
    } yield {
      serverBindingOption = Some(serverBinding)
      new SyslogStreamServer
    }
  }

  def close()(implicit ec: ExecutionContext): Future[Unit] = {
    serverSource.success(ByteString.empty) // dummy value to be dropped above
    serverBindingOption match {
      case Some(serverBinding) ⇒ serverBinding.unbind()
      case None ⇒ Future[Unit] {}
    }
  }

这是关闭服务器的好方法吗? (用于部署等)

如果有人可以审核并评论上述close()实现的有效性。我们试图证明或反驳这些代码是否满足所有要求,并想知道我们是否应该首先成功完成流程的源代码,或者首先取消绑定serverBinding?任何评论/批评都非常感谢。提前谢谢!

0 个答案:

没有答案