【问题标题】:Shut down Akka HTTP app关闭 Akka HTTP 应用程序
【发布时间】:2017-09-18 19:11:20
【问题描述】:

我有一个正在运行的 Akka HTTP 应用程序,我想将其关闭。

对我来说,在 SBT does not work 中按 Ctrl + C(我的 shell 目前是适用于 Windows 的 Git Bash)。

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

【问题讨论】:

    标签: scala akka akka-http


    【解决方案1】:

    this thread 中获得灵感,我为我的应用程序添加了一条关闭应用程序的路由:

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

    其中system 是应用的ActorSystem

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

    curl http://localhost:5000/shutdown
    

    编辑:

    能够远程关闭服务器对于生产代码来说不是一个好主意。在 cmets 中,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())
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2016-10-12
    • 2018-02-16
    • 1970-01-01
    相关资源
    最近更新 更多