【发布时间】:2013-12-10 18:25:57
【问题描述】:
最近我深入研究了一些使用 API 的工作。该 API 使用 Unirest http 库来简化从 Web 接收的工作。自然,由于数据是从 API 服务器调用的,因此我尝试通过对 API 进行异步调用来提高效率。我的想法结构如下:
- 通过返回期货结果创建数据数组
- 显示数据 + 从数据中收集的其他信息
因此,我需要在开始第二步之前返回所有数据。我的代码如下:
Future < HttpResponse < JsonNode > > future1 = Unirest.get("https://example.com/api").asJsonAsync(new Callback < JsonNode > () {
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void completed(HttpResponse < JsonNode > response) {
System.out.println(response.getBody().toString());
responses.put(response);
}
public void cancelled() {
System.out.println("The request has been cancelled");
}
});
Future < HttpResponse < JsonNode > > future2 = Unirest.get("https://example.com/api").asJsonAsync(new Callback < JsonNode > () {
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void completed(HttpResponse < JsonNode > response) {
System.out.println(response.getBody().toString());
responses.put(response);
}
public void cancelled() {
System.out.println("The request has been cancelled");
}
});
doStuff(responses);
我将如何做到只有在两个期货都完成后才调用 doStuff?
【问题讨论】:
-
可能想看看
ExecutorCompletionService,但如果任何响应完成,您可以做一些事情。
标签: java api concurrency future