在 Akka 中等待函数完成或 5 秒后超时

Either wait for a function to finish or timeout after 5 seconds in Akka

我试图等待函数完成或 5 秒后超时,但无论我做什么,我都无法阻止以下异常。有趣的是它被父演员抓住了:

java.util.concurrent.TimeoutException: Futures timed out after [5 seconds]

我尝试过的解决方案之一(来自this问题):

val f = Future { dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec() }
val result: Try[InputStream] = Await.ready(f, 5.seconds).value.get

val resultEither = result match {
  case Success(t) => log.info("right")
  case Failure(e) => log.info("left")
}

确实可以通过 akka 请求模式实现这一点。但是有一个不同的解决方案可以在没有 akka 的情况下使用。

将您的阻塞 Await 代码包装到另一个 Future 并注册 onComplete 函数

import concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success, Try}

val sleepTimeout = 1*1000

val f = Future( Thread.sleep(sleepTimeout); Try(10))
val timeoutFuture = Future(Await.result(f, 5.seconds))
timeoutFuture.onComplete {
  case Success(Success(t))  => println(t)
  case Success(Failure(ex))  => println("error on Try" + ex.getMessage)
  case Failure(e) => println("timeout " + e.getMessage)
}

解释匹配案例

  • Success(Success(t))首先Success是针对timeoutFuture的,表示没有超时。第二个 Success 用于 Try - 表示没有抛出异常。
  • Success(Failure(ex)) 与第一个相同,但 Try
  • 内有例外
  • Failure(e) 这里是处理超时的地方。