Play 2.2操作未与Web Service响应处理程序并行处理 [英] Play 2.2 action not processed in parallel with web service response handler
问题描述
public class Application extends Controller {
@BodyParser.Of(BodyParser.Json.class)
public static Result action1() {
WS.url(WS_URL).get().map(new Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
});
return ok();
}
@BodyParser.Of(BodyParser.Json.class)
public static Result action2() {
return ok();
}
}
客户端首先调用action1()
,然后调用action2()
.但是,似乎Play在那10秒钟后处理了第二个请求.我以为Play会在单独的线程中处理来自Web服务的响应,但这似乎并非如此.在这种情况下,如果我想睡觉或在超时后执行一些代码而不中断服务器处理其他请求,该怎么办?
The client first calls action1()
, then, it calls action2()
. However, it seems that Play process the second request after those 10 seconds. I thought that responses from web services are processed by Play in separate threads, but it seems that's not true. In this case, what should I do if I want to sleep or to execute some code after a timeout, without interrupting the server from serving other requests?
当来自WS的响应在客户端调用action2()之前到达时会发生.
this happens when the response from the WS arrives before the client calls action2().
推荐答案
不太确定您要实现的目标,但是下面的代码将在WS调用返回与返回WS调用之间插入10秒的延迟.好的结果:
Not really sure what you're trying to achieve, but the code below will insert a 10 second delay between when the WS call returns, and when it returns an ok result:
public static F.Promise<SimpleResult> action1() {
return WS.url(WS_URL).get().flatMap(new Function<WS.Response, F.Promise<WS.Response>>() {
public F.Promise<WS.Response> apply(WS.Response response) {
return F.Promise.timeout(response, 100000);
}
}).map(new Function<WS.Response, SimpleResult>() {
public SimpleResult apply(WS.Response response) {
return ok();
}
};
}
要了解Play的线程池,请阅读以下内容:
To understand Play's thread pools, read this:
http://www.playframework.com/documentation/2.2.x/ThreadPools
要了解Play如何实现承诺,请阅读以下内容:
To understand how Play works with promises, read this:
http://www.playframework.com/documentation/2.2.x/JavaAsync
这篇关于Play 2.2操作未与Web Service响应处理程序并行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!