如何处理响应超时? [英] How to handle response timeout?

查看:125
本文介绍了如何处理响应超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在akka-http路由中,我可以返回 Future 作为隐式转换为 ToResponseMarshaller 的响应。

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

是否有一些方法可以解决此将来的超时问题?还是路由级别的连接超时?还是一种方法是使用 Await()函数?

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
 }


推荐答案

向异步操作添加超时意味着创建新的Future通过操作本身或通过超时来完成:

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
  )

第二个Future也可以成功替换错误,具体取决于错误

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

请注意:所提供的代码示例包含无效代码,在Future上注册onComplete处理程序仅对副作用有意义,但您似乎想要转换Future的值并从中创建一个HttpEntity。应该使用 map recover 来完成:

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")) }

这将是总收益传递给 complete 指令的值。

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

这篇关于如何处理响应超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆