Play 2 允许您通过 AsyncResult 进行异步 Web 服务调用,这不会阻塞线程:
public static Result feedTitle(String feedUrl) {
return async(
WS.url(feedUrl).get().map(
new Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("Feed title:" + response.asJson().findPath("title"));
}
}
)
);
}
这仅在您执行简单的事情(例如将 WS 调用的结果直接传递给用户)时才有效。但是,如果您必须对结果进行额外的操作怎么办?
查看文档,您似乎可以这样做:
Promise<Response> promise = WS.url("http://some.website.com").get();
Response response = promise.get(); // I've got the result, but I've also blocked
这显然是不理想的。有没有办法在允许 Play 将执行传递给其他线程的同时进行异步调用?