关闭Akka HTTP应用程序

Mat*_*aun 9 scala akka akka-http

我有一个正在运行的Akka HTTP应用程序,我想关闭它.

在SBT Ctrl+ 不适用于我(我的shell目前是用于Windows的Git Bash).C

什么是优雅关闭Akka应用程序的推荐方法?

Mat*_*aun 8

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

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

system应用程序的ActorSystem在哪里.

鉴于这条路线,我现在可以关闭我的应用程序了

curl http://localhost:5000/shutdown
Run Code Online (Sandbox Code Playgroud)

编辑:

能够远程关闭服务器对于生产代码来说不是一个好主意.在评论中,Henrik指出了一种通过点击EnterSBT控制台来关闭服务器的不同方式:

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

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

// 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())
Run Code Online (Sandbox Code Playgroud)

  • 在此示例中,它们使用相同的方法调用显示类似的退出方式,但是按下return而不是打开连接.如果您可以轻松地物理访问正在运行的计算机,则可能更为可取.http://doc.akka.io/docs/akka-http/current/scala/http/routing-dsl/index.html#minimal-example (2认同)