gpt4 book ai didi

Scala future 应用程序在完成之前终止

转载 作者:行者123 更新时间:2023-12-01 12:26:59 24 4
gpt4 key购买 nike

只是试图让我的第一个 future 使用并运行并进行类似于 Akka in Action MEAP 书中概述的示例的测试。我想调用 Web 服务并在将来返回结果。我正在使用 scalaxb 访问网络服务。我已经概述了下面的代码,但是当我运行它时,应用程序会终止而无需等待服务的响应。也许有人可以告诉我我错过了什么?

import scala.util._
import control.NonFatal
import scala.concurrent._
import ExecutionContext.Implicits.global

object Test {


val service = (new MyServiceBindings with scalaxb.Soap11Clients with scalaxb.DispatchHttpClients {}).service

def test = {

val f = future {

service.someCall() match {
case Right(resp) => resp
case Left(fault) => throw new Exception("Fault: " + fault)}
}
}

f.onComplete {
case Success(resp) => println("Resp: " + resp)
case Failure(NonFatal(e)) => println("Fail: " + e)
}
}

def main(args: Array[String]): Unit = {
test
}
}

最佳答案

它终止是因为在您的测试中执行的主线程已经完成。 Dispatch 库内部使用的线程不会阻止程序退出。

您需要等待 future ,因为这是您的测试应用程序正在做的唯一事情。把它放在 onComplete 语句之后。
import scala.concurrent.duration._
Await.ready(f, 10.seconds)

现在请记住,这通常是不好的做法。你在这里需要它,因为你的测试应用程序没有做任何其他事情,但在一个真正的应用程序中,你不想在每次 future 调用之后阻塞,因为这会否定使用 future 的意义。

关于Scala future 应用程序在完成之前终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23547963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com