How to handle response timeout?

ぐ巨炮叔叔 提交于 2019-12-21 04:53:29

问题


In akka-http routing I can return Future as a response that implicitly converts to ToResponseMarshaller.

Is there some way to handle timeout of this future? Or timeout of connection in route level? Or one way is to use Await() function?

Right now client can wait response forever.

complete {
   val future = for {
     response <- someIOFunc()
     entity <- someOtherFunc()
   } yield entity
   future.onComplete({
     case Success(result) =>
       HttpResponse(entity = HttpEntity(MediaTypes.`text/xml`, result))
     case Failure(result) =>
       HttpResponse(entity = utils.getFault("fault"))
   })
   future
 }

回答1:


Adding a timeout to an asynchronous operation means creating a new Future that is completed either by the operation itself or by the timeout:

import akka.pattern.after
val future = ...
val futureWithTimeout = Future.firstCompletedOf(
    future ::
    after(1.second, system.scheduler)(Future.failed(new TimeoutException)) ::
    Nil
  )

The second Future could also hold a successful result that replaces the error, depending on what exactly it is that you want to model.

As a side note: the presented code sample contains dead code, registering an onComplete handler on a Future only makes sense for side-effects but you seem to want to transform the Future’s value and create an HttpEntity from it. That should be done using map and recover:

future
  .map(result => HttpResponse(entity = HttpEntity(MediaTypes.`text/xml`, result)))
  .recover { case ex => HttpResponse(entity = utils.getFault("fault")) }

This would then be the overall return value that is passed to the complete directive.



来源:https://stackoverflow.com/questions/29318411/how-to-handle-response-timeout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!