gpt4 book ai didi

java - Play Framework wait() 使应用程序表现得很奇怪

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:36 25 4
gpt4 key购买 nike

我在使用 Controller 的方法await(Future future)时遇到了一些奇怪的问题。

每当我在代码中的任何位置添加等待行时,一些与我放置等待的位置无关的 GenericModel 就会开始错误加载,并且我无法访问它们的任何属性。

最奇怪的是,如果我在项目中任何地方的另一个完全不同的 java 文件中更改某些内容,我猜 play 将尝试重新编译,在那一刻它开始完美工作,直到我再次清理 tmp。

最佳答案

当您在 Controller 中使用await时,它会进行字节码增强以将单个方法分解为两个线程。这很酷,但绝对是 Play1 的“黑魔法”技巧之一。但是,这是 Play 经常表现得很奇怪并且需要重新启动(或者如您所发现的,某些代码更改)的地方 - 它可能表现得很奇怪的另一个地方是当您更改模型类时。

http://www.playframework.com/documentation/1.2.5/asynchronous#SuspendingHTTPrequests

To make it easier to deal with asynchronous code we have introduced continuations. Continuations allow your code to be suspended and resumed transparently. So you write your code in a very imperative way, as:

public static void computeSomething() { Promise delayedResult = veryLongComputation(…); String result = await(delayedResult); render(result); }

In fact here, your code will be executed in 2 steps, in 2 different hreads. But as you see it, it’s very transparent for your application code.

Using await(…) and continuations, you could write a loop:

 public static void loopWithoutBlocking() {
for(int i=0; i<=10; i++) {
Logger.info(i);
await("1s");
}
renderText("Loop finished"); }

And using only 1 thread (which is the default in development mode) to process requests, Play is able to run concurrently these loops for several requests at the same time.

<小时/>

回复您的评论:

 public static void generatePDF(Long reportId) {
Promise<InputStream> pdf = new ReportAsPDFJob(report).now();
InputStream pdfStream = await(pdf);
renderBinary(pdfStream);

ReportAsPDFJob 只是一个重写了 doJobWithResult 的 play Job 类 - 因此它返回对象。请参阅http://www.playframework.com/documentation/1.2.5/jobs了解有关工作的更多信息。

调用job.now()会返回一个future/promise,您可以像这样使用它:await(job.now())

关于java - Play Framework wait() 使应用程序表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16113609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com