簡體   English   中英

在Akka-http中處理SIGTERM

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM