2017-04-21 49 views

回答

6

this thread获得灵感,我加入到我的应用程序路由时,关闭应用程序:

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

其中system是应用程序的ActorSystem

鉴于这条路,现在我可以

curl http://localhost:5000/shutdown 

编辑关闭我的应用程序:

如果能够远程关闭服务器不是生产代码是个好主意。在评论,Henrik指出,通过打在SBT控制台输入关闭服务器以不同的方式:

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()) 
+2

在这个例子中,他们使用相同的方法调用显示了类似的退出方式,但是通过按回车而不是打开连接。如果您可以轻松访问正在运行的计算机,则可能更可取。 http://doc.akka.io/docs/akka-http/current/scala/http/routing-dsl/index.html#minimal-example – Henrik