关闭Akka HTTP应用程序

hwazgwia  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(148)

我有一个正在运行的Akka HTTP应用程序,我想关闭它。
为我在SBT does not work中按下Ctrl + C(我的shell目前是Windows的Git Bash)。
建议使用什么方法来正常关闭Akka应用程序?

rm5edbpk

rm5edbpk1#

从这个线程中获得灵感,我向应用程序添加了一个关闭应用程序的路由:

def shutdownRoute: Route = path("shutdown") {
  Http().shutdownAllConnectionPools() andThen { case _ => system.terminate() }
  complete("Shutting down app")
}

其中system是应用程序的ActorSystem
通过这种方法,我现在可以关闭我的应用程序

curl http://localhost:5000/shutdown

编辑:

能够远程关闭服务器对于生产代码来说并不是一个好主意。在注解中,Henrik指出了一种不同的方法,通过在SBT控制台中按Enter键来关闭服务器:

StdIn.readLine()
// Unbind from the port and shut down when done
bindingFuture
  .flatMap(_.unbind())
  .onComplete(_ => system.terminate())

对于上下文,我将上述代码放在服务器初始化的末尾:

// Gets the host and a port from the configuration
val host = system.settings.config.getString("http.host")
val port = system.settings.config.getInt("http.port")

implicit val materializer = ActorMaterializer()

// bindAndHandle requires an implicit ExecutionContext
implicit val ec = system.dispatcher

import akka.http.scaladsl.server.Directives._
val route = path("hi") {
  complete("How's it going?")
}

// Starts the HTTP server
val bindingFuture: Future[ServerBinding] =
  Http().bindAndHandle(route, host, port)

val log = Logging(system.eventStream, "my-application")

bindingFuture.onComplete {
  case Success(serverBinding) =>
    log.info(s"Server bound to ${serverBinding.localAddress}")

  case Failure(ex) =>
    log.error(ex, "Failed to bind to {}:{}!", host, port)
    system.terminate()
}

log.info("Press enter key to stop...")
// Let the application run until we press the enter key
StdIn.readLine()
// Unbind from the port and shut down when done
bindingFuture
  .flatMap(_.unbind())
  .onComplete(_ => system.terminate())

相关问题