在java中播放框架异步调用
我使用下面的代码来调用Web服务。Play的框架非阻塞动作很棒。唯一的问题是,在将响应发送到视图之前,我希望存储响应并对其进行操作在java中播放框架异步调用,java,asynchronous,playframework,promise,Java,Asynchronous,Playframework,Promise,我使用下面的代码来调用Web服务。Play的框架非阻塞动作很棒。唯一的问题是,在将响应发送到视图之前,我希望存储响应并对其进行操作 public static Promise<JsonNode> classService(String id) { String urlS = "www.service.api.com"; Promise<WSResponse> responsePromise = WS.url(urlS).get();
public static Promise<JsonNode> classService(String id) {
String urlS = "www.service.api.com";
Promise<WSResponse> responsePromise = WS.url(urlS).get();
Promise<JsonNode> resultPromise = responsePromise
.map(new Function<WSResponse, JsonNode>() {
@Override
public JsonNode apply(WSResponse response) throws Throwable {
JsonNode searchResponse = response.asJson();
return searchResponse;
}
});
return resultPromise;
}
当我尝试将数据存储在while循环中时,代码会出错。因此,当播放完成时,如何存储数据。您可以将显式超时设置为随机毫秒。在使用/存储数据之前,您可以使用等待所有结果 因此,从您的while循环中,我们将存储承诺:
List<F.Promise<JsonNode>> promises = new ArrayList<F.Promise<JsonNode>>();
while(dataIter.hasNext()){
JsonNode tempNode = dataIter.next();
String id = tempNode.path("id").toString();
promises.add(classService(id));
}
然后在所有结果出来后,立即对数据执行任何需要执行的操作
F.Promise.sequence(promises).map(new Function<List<JsonNode>, Response>() {
@Override
public Response apply(List<JsonNode> data) throws Throwable {
// Do stuff with your data, or store it wherever
return ok("Here is the result")
}
}
当然,如果您需要在JsonNode级别操作数据,即不需要集合的其余部分,那么您可以在classService中已有的映射中进行操作
F.Promise.sequence(promises).map(new Function<List<JsonNode>, Response>() {
@Override
public Response apply(List<JsonNode> data) throws Throwable {
// Do stuff with your data, or store it wherever
return ok("Here is the result")
}
}