gpt4 book ai didi

scala - 使用 spray 和 futures 超时检索 http 响应

转载 作者:可可西里 更新时间:2023-11-01 16:36:49 26 4
gpt4 key购买 nike

我正在尝试找出使用超时从 GET http 请求中检索内容的最佳方法。我花了很多时间试图找出最佳方法,但我有点不确定。

基本上我只想有一个选项,如果在超时之前没有响应,则返回 None,否则返回内容。

谢谢

最佳答案

所以我想您正在尝试解决 2 个问题。如何在配置中定义特定超时,以及如何在超时发生时对其进行管理。

  • 定义 http 客户端超时:您需要更新您的 application.conf 以覆盖 default configuration of the http client .例如:

    spray.can {
    client {
    request-timeout = 20s
    }
    }
  • 管理超时:当您使用 spray client ,您将使用将运行请求的管道。它将是一个类似于 (HttpRequest) => Future[ObjectResponse] 的函数。结果将是您定义的对象的 Future,在我的示例中,ObjectResponse,您可以解析 future 。如果超时,Future 将变为 RequestTimeoutException .然后您将能够使用 recover 处理超时异常。所以你的代码看起来像这样:

    def sendRequestFunction(...): Future[ObjectResponse] = {...}

    sendRequestFunction(parameters) map (Option) // In case we get an object, we will have a Some(obj)
    recover {
    case e: RequestTimeoutException => None
    }

关于scala - 使用 spray 和 futures 超时检索 http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37311336/

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