Scala 使用带超时的spray和futures检索http响应

Scala 使用带超时的spray和futures检索http响应,scala,http,httprequest,spray,Scala,Http,Httprequest,Spray,我正在尝试找出使用超时从GET http请求检索内容的最佳方法。我花了很多时间试图找出最好的方法,但我有点不确定 基本上,我只想有一个选项,如果响应没有在超时之前出现,则返回None,否则返回内容 谢谢您可以尝试以下方法: timedOutFuture = after(duration = duration, using = system.scheduler) { Future.successfull(None) } Future.firstCompletedOf(Seq(youHtt

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

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


谢谢

您可以尝试以下方法:

timedOutFuture = after(duration = duration, using = system.scheduler) {
   Future.successfull(None)
 }

Future.firstCompletedOf(Seq(youHttpRequestFuture, timedOutFuture))
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
}

希望它能有所帮助,所以我想您正在尝试解决两个问题。如何在配置中定义特定超时,以及如何在超时发生时管理超时

  • 定义http客户端超时:您需要更新
    application.conf
    以覆盖http客户端超时。e、 g:

  • 管理超时:在使用时,将使用运行请求的
    管道。它将是一个类似于
    (HttpRequest)=>Future[ObjectResponse]
    的函数。 结果将是您定义的对象的
    未来
    ObjectResponse
    在我的示例中,您可以解析未来。如果存在超时,则未来的
    将变为一个。然后,您将能够使用
    recover
    处理超时异常。因此,您的代码将如下所示:

    timedOutFuture = after(duration = duration, using = system.scheduler) {
       Future.successfull(None)
     }
    
    Future.firstCompletedOf(Seq(youHttpRequestFuture, timedOutFuture))
    
    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
    }
    

您正在使用spray http客户端吗?是的,我正在使用spray