[英]Handle SIGTERM in akka-http
当前(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? 我不确定..
谢谢!
从这里的答案中得到的解决方案:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.