繁体   English   中英

Play框架:根据控制器承诺处理超时

[英]Play Framework: handling timeout over controller promise

我所有应用程序的控制器(Play Framework 2.2.4,Java)都返回F.Promise:现在有一个控制器,我可以切换到另一个akka上下文,因为它的计算时间会更长。 上下文切换相当简单,因为您可以使用api:

return F.Promise.promise(...,executionContext)

并在application.conf中配置自定义executionContext。 现在问题出在计算时间超过指定的时间量时(让它超过20秒):我无法实现Promise超时。考虑到我不想调用get(20,TimeUnit.SECONDS )的promise方法,因为我确定play会做到这一点。我在akka执行服务中搜索了一些配置属性,发现了这个

thread-pool-executor {
    # Keep alive time for threads
    keep-alive-time = 60s

    # Min number of threads to cap factor-based core number to
    core-pool-size-min = 8

    # The core pool size factor is used to determine thread pool core size
    # using the following formula: ceil(available processors * factor).
    # Resulting size is then bounded by the core-pool-size-min and
    # core-pool-size-max values.
    core-pool-size-factor = 3.0

    # Max number of threads to cap factor-based number to
    core-pool-size-max = 64

    # Minimum number of threads to cap factor-based max number to
    # (if using a bounded task queue)
    max-pool-size-min = 8

    # Max no of threads (if using a bounded task queue) is determined by
    # calculating: ceil(available processors * factor)
    max-pool-size-factor  = 3.0

    # Max number of threads to cap factor-based max number to
    # (if using a  bounded task queue)
    max-pool-size-max = 64

    # Specifies the bounded capacity of the task queue (< 1 == unbounded)
    task-queue-size = -1

    # Specifies which type of task queue will be used, can be "array" or
    # "linked" (default)
    task-queue-type = "linked"

    # Allow core threads to time out
    allow-core-timeout = on
  }

但是keep-alive-timeallow-core-timeout属性都不能使长时间的计算承诺超时。

我试图将返回类型更改为:

F.Promise<Result> original = F.Promise.promise(...,customExecutionService);
return F.promise.timeout(original,10,TimeUnit.SECONDS);

但这只是将执行推迟了10秒钟。(超时方法文档非常混乱)

我尝试过的其他片段是:

F.Promise<Result> original = F.Promise.promise(...,customExecutionService);
  return F.promise.timeout(original,10,TimeUnit.SECONDS).get(10,TimeUnit.SECONDS);

但是这次超时是外部包装器的承诺。

因此,我现在得出的结论是,我必须编写自己的自定义executeService,以设置超时侦听器并自行抛出TimeoutException,但是我确信要实现这一目标,可以采取一些更简单的方法。

我找到了一种解决方案,方法是使用以下代码包装原始响应(不会超时的响应):

Future<T> error = after(Duration.create(delay,unit),Akka.system().scheduler(),main,
                Futures.failed(new TimeoutException("Future timed out")));

return Promise.wrap(Futures.firstCompletedOf(
    Lists.newArrayList(original.wrapped(),error), main));

```

其中主要是主要的执行上下文, 之后从阿卡模式拍摄。 基本上,如果原始的承诺花费的时间超过了错误所传递的持续时间 ,则将来会通过抛出Timeout Exception来启动。

我将其放在过滤器中,以便每个带有该过滤器注释的控制器都具有相同的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM