akka 为什么会立即终止?

z9gpfhce  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(215)

我有下面的代码,我想知道,为什么当我执行它时,它会立即停止:

  1. import akka.actor.ActorSystem
  2. import akka.http.scaladsl.Http
  3. import akka.http.scaladsl.model._
  4. import akka.http.scaladsl.server.Directives._
  5. import akka.stream.ActorMaterializer
  6. import scala.io.StdIn
  7. object WebServer {
  8. def main(args: Array[String]) {
  9. implicit val system = ActorSystem("my-system")
  10. implicit val materializer = ActorMaterializer()
  11. // needed for the future flatMap/onComplete in the end
  12. implicit val executionContext = system.dispatcher
  13. val route =
  14. path("hello") {
  15. get {
  16. complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
  17. }
  18. }
  19. val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
  20. bindingFuture
  21. .flatMap(_.unbind()) // trigger unbinding from the port
  22. .onComplete(_ => system.terminate()) // and shutdown when done
  23. }
  24. }

字符串
正如你所看到的,它是一个简单的Web应用程序,它不应该停止运行。
但是当我删除以下代码时:

  1. bindingFuture
  2. .flatMap(_.unbind()) // trigger unbinding from the port
  3. .onComplete(_ => system.terminate()) // and shutdown when done


它会一直运行直到我终止它。
问题是,为什么没有

  1. bindingFuture
  2. .flatMap(_.unbind()) // trigger unbinding from the port
  3. .onComplete(_ => system.terminate()) // and shutdown when done


申请不会终止吗

o4hqfura

o4hqfura1#

你的bindingFuture在这两种情况下都完成了。

  1. bindingFuture
  2. .flatMap(_.unbind()) // trigger unbinding from the port
  3. .onComplete(_ => system.terminate()) // and shutdown when done

字符串
然后,unbindterminate会在服务器侦听时立即运行,这会导致程序立即完成。
如果你忽略了这段代码,那么你的程序会一直运行,直到所有的线程都运行完。因为参与者系统是在后台运行线程的,你从来不会终止它,所以这种情况永远不会发生,你必须杀死你的程序来停止它。
一种在任何按键时都能正常关机的方法是使用这个(取自official documentation

  1. val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
  2. println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
  3. StdIn.readLine() // let it run until user presses return
  4. bindingFuture
  5. .flatMap(_.unbind()) // trigger unbinding from the port
  6. .onComplete(_ => system.terminate()) // and shutdown when done


在这种情况下,StdIn.readLine()将阻塞主线程,直到按下某个键,此时执行元系统和http服务器将关闭。
如果你想等待一个自定义的“事件”而不是一个按键,你可以简单地等待一个自定义的Future,如下所示:

  1. // Just build a Future that will get completed when you want to shutdown
  2. // This can be done manually using a `Promise[Unit]`, but you might also be using
  3. // a library that will give you a Future to wait on.
  4. val myFuture: Future[Unit] = ???
  5. myFuture.flatMap(_ => bindingFuture)
  6. .flatMap(_.unbind())
  7. .onComplete(_ => system.terminate())

展开查看全部

相关问题