【问题标题】:Handle SIGTERM in akka-http在 akka-http 中处理 SIGTERM
【发布时间】:2018-07-18 11:35:27
【问题描述】:

当前 (10.1.3) Akka HTTP 文档:

https://doc.akka.io/docs/akka-http/current/server-side/graceful-termination.html

使用此代码示例讨论优雅终止:

import akka.actor.ActorSystem
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import scala.concurrent.duration._

implicit val system = ActorSystem()
implicit val dispatcher = system.dispatcher
implicit val materializer = ActorMaterializer()

val routes = get {
  complete("Hello world!")
}

val binding: Future[Http.ServerBinding] =
    Http().bindAndHandle(routes, "127.0.0.1", 8080)

// ...
// once ready to terminate the server, invoke terminate:
val onceAllConnectionsTerminated: Future[Http.HttpTerminated] =
Await.result(binding, 10.seconds)
  .terminate(hardDeadline = 3.seconds)

// once all connections are terminated,
// - you can invoke coordinated shutdown to tear down the rest of the system:
onceAllConnectionsTerminated.flatMap { _ ⇒
  system.terminate()
}

我想知道在什么时候调用它,评论指出:

// once ready to terminate the server

这究竟是什么意思,即谁/什么决定了服务器准备好终止?

我是否必须将上面的关闭代码放在某个钩子函数中,以便在收到 SIGTERM 的 Akka HTTP 上调用它?

我试过把这个放到关机钩子里:

CoordinatedShutdown(system).addCancellableJvmShutdownHook{
  // once ready to terminate the server, invoke terminate:
  val onceAllConnectionsTerminated: Future[Http.HttpTerminated] =
  Await.result(binding, 10.seconds)
    .terminate(hardDeadline = 3.seconds)

  // once all connections are terminated,
  // - you can invoke coordinated shutdown to tear down the rest of the system:
  onceAllConnectionsTerminated.flatMap { _ ⇒
    system.terminate()
  }
}

但是正在进行的请求会在发送 SIGTERM (kill ) 后立即结束,而不是完成。

我还发现了一种与https://github.com/akka/akka-http/issues/1210#issuecomment-338825745略有不同的关机方式:

CoordinatedShutdown(system).addTask(
    CoordinatedShutdown.PhaseServiceUnbind, "http_shutdown") { () =>

    bind.flatMap(_.unbind).flatMap { _ =>
      Http().shutdownAllConnectionPools
    }.map { _ =>
      Done
    }
  }

也许我应该用它来处理 SIGTERM?我不确定..

谢谢!

【问题讨论】:

    标签: scala akka akka-http


    【解决方案1】:

    从这里的答案中获取的解决方案:

    https://discuss.lightbend.com/t/graceful-termination-on-sigterm-using-akka-http/1619

    CoordinatedShutdown(system).addTask(
        CoordinatedShutdown.PhaseServiceUnbind, "http_shutdown") { () =>
    
        bind.flatMap(_.terminate(hardDeadline = 1.minute)).map { _ =>
          Done
        }
      }
    

    对我来说,主要部分是增加 akka.coordinated-shutdown.default-phase-timeout,因为完成请求处理所需的时间比默认的 5 秒要长。您也可以只增加该阶段的超时时间。我的日志中有以下消息:

    Coordinated shutdown phase [service-unbind] timed out after 5000 milliseconds
    

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 2020-02-07
      • 1970-01-01
      • 2016-11-09
      • 2011-02-27
      • 2021-09-23
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      相关资源
      最近更新 更多