首页 > 解决方案 > 在 Playframework 中忽略 withRequestTimeout

问题描述

当我从 playframework 使用 HTTP 客户端时无法设置超时。这是我的代码:

val request: Future[WSResponse] = WS
    .url(url)
    .withAuth(user, password, WSAuthScheme.BASIC)
    //5 minute timeout in milliseconds
    .withRequestTimeout(300000)
    .put("")

这不会给我一个错误,但请求将在 2 分钟后直接超时。是否需要设置其他内容才能使用超时?

更新:我使用的是 2.4.8 版本的 playframework。看起来这个版本有以下错误:https ://github.com/playframework/playframework/issues/4846

但是,建议的修补程序不适合我。

val request: Future[WSResponse] = WS
    .url(url)
    .asInstanceOf[NingWSRequest]
    .copy(requestTimeout = Some(-1))
    .withAuth(user, password, WSAuthScheme.BASIC)
    .withRequestTimeout(-1)
    .put("")

两者都会在 2 分钟后给我一个超时。

标签: scalaplayframeworkplayframework-2.4

解决方案


我不能保证这对你有用,但它似乎对我有用,你可能会适应它:

val httpClient = Try(WS.underlying.asInstanceOf[AsyncHttpClient])
  .getOrElse(throw new NotImplementedError("Unsupported HTTP client"))
val putBuilder = httpClient.preparePut(url)
putBuilder.setRequestTimeout(-1).addHeader(user, "Basic " + password)
val promise = Promise[Response]()
httpClient.executeRequest(putBuilder.build(),
  new AsyncCompletionHandler[Response] {
    def onCompleted(response: Response): Response = {
      promise.success(response)
      response
    }
    def onThrowable(t: Throwable): Unit = {
      promise.failure(t)
      super.onThrowable(t)
    }
  }
)

祝你好运。


推荐阅读