java - 如何处理多个 ListenableFuture? ( Spring )

标签 java spring asynchronous

我正在编写一个 Controller ,我需要使其异步。我如何处理 ListenableFuture 的列表?因为我有一个 URL 列表,需要一一发送 GET 请求,那么最好的解决方案是什么?

@RequestMapping(value = "/repositories", method = RequestMethod.GET)
    private void getUsername(@RequestParam(value = "username") String username) {
        System.out.println(username);
        List<ListenableFuture> futureList = githubRestAsync.getRepositoryLanguages(username);
        System.out.println(futureList.size());
}

在我使用的服务中List<ListanbleFuture>这似乎不起作用,因为它是异步的,在 Controller 方法中我不能有 futureList 的大小运行 for loop在其上进行回调。

public List<ListenableFuture> getRepositoryLanguages(String username){
      return getRepositoryLanguages(username, getUserRepositoriesFuture(username));
    }

private ListenableFuture getUserRepositoriesFuture(String username) throws HttpClientErrorException {
        HttpEntity entity = new HttpEntity(httpHeaders);
        ListenableFuture future = restTemplate.exchange(githubUsersUrl + username + "/repos", HttpMethod.GET, entity, String.class);
        return future;
    }
private List<ListenableFuture> getRepositoryLanguages(final String username, ListenableFuture<ResponseEntity<String>> future) {
        final List<ListenableFuture> futures = new ArrayList<>();
        future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
            @Override
            public void onSuccess(ResponseEntity<String> response) {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    repositories = mapper.readValue(response.getBody(), new TypeReference<List<Repositories>>() {
                    });
                    HttpEntity entity = new HttpEntity(httpHeaders);
                    System.out.println("Repo size: " + repositories.size());
                    for (int i = 0; i < repositories.size(); i++) {
                        futures.add(restTemplate.exchange(githubReposUrl + username + "/" + repositories.get(i).getName() + "/languages", HttpMethod.GET, entity, String.class));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("FAILURE in getRepositoryLanguages: " + throwable.getMessage());
            }
        });

        return futures;
    }

我应该使用类似 ListenableFuture<List> 的东西吗?而不是List<ListenableFuture>

最佳答案

您似乎有一个 List<ListenableFuture<Result>> ,但你想要 ListenableFuture<List<Result>> ,这样您就可以在所有 future 完成时采取一项操作。

public static <T> ListenableFuture<List<T>> allOf(final List<? extends ListenableFuture<? extends T>> futures) {
    // we will return this ListenableFuture, and modify it from within callbacks on each input future
    final SettableListenableFuture<List<T>> groupFuture = new SettableListenableFuture<>();

    // use a defensive shallow copy of the futures list, to avoid errors that could be caused by
    // someone inserting/removing a future from `futures` list after they call this method
    final List<? extends ListenableFuture<? extends T>> futuresCopy = new ArrayList<>(futures);

    // Count the number of completed futures with an AtomicInt (to avoid race conditions)
    final AtomicInteger resultCount = new AtomicInteger(0);
    for (int i = 0; i < futuresCopy.size(); i++) {
        futuresCopy.get(i).addCallback(new ListenableFutureCallback<T>() {
            @Override
            public void onSuccess(final T result) {
                int thisCount = resultCount.incrementAndGet();

                // if this is the last result, build the ArrayList and complete the GroupFuture
                if (thisCount == futuresCopy.size()) {
                   List<T> resultList = new ArrayList<T>(futuresCopy.size());
                    try {
                        for (ListenableFuture<? extends T> future : futuresCopy) {
                            resultList.add(future.get());
                        }
                        groupFuture.set(resultList);
                    } catch (Exception e) {
                        // this should never happen, but future.get() forces us to deal with this exception.
                        groupFuture.setException(e);
                    }
                }
            }

            @Override
            public void onFailure(final Throwable throwable) {
                groupFuture.setException(throwable);

                // if one future fails, don't waste effort on the others
                for (ListenableFuture future : futuresCopy) {
                    future.cancel(true);
                }
            }
        });
    }

    return groupFuture;
}

关于java - 如何处理多个 ListenableFuture? ( Spring ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36387292/

相关文章:

节点包含链表的 Java 二叉搜索树

java - 为什么 java.net.HttpURLConnection 响应无法识别的字符?

mysql - Spring boot - h2和mysql的配置文件

java - 如何在Spring中使用WebLogic提供的JNDI DataSource?

java - 如何获取图像的高度和宽度?

java - 在 Java 中比较 TreeMap 键和值

java - 在自定义 Eclipse 透视图中显示 View

java - Spring Boot Tomcat配置,从容器迁移到嵌入式

c# - 我如何强制等待在同一线程上继续?

ios - UITableViewCell内存中的异步图像加载问题