java – 子请求的CompletableFuture

前端之家收集整理的这篇文章主要介绍了java – 子请求的CompletableFuture前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图理解Java 8中的@R_301_5@.作为其中的一部分,我正在尝试进行一些REST调用以巩固我的理解.我正在使用这个库来进行REST调用https://github.com/AsyncHttpClient/async-http-client.

请注意,此库返回GET调用的Response对象.

以下是我要做的事情:

>调用此URL,该URL提供用户列表:https://jsonplaceholder.typicode.com/users
>使用GSON将响应转换为用户对象列表.
>迭代列表中的每个User对象,获取userID,然后从以下URL获取用户发布的帖子列表:https://jsonplaceholder.typicode.com/posts?userId=1
>使用GSON将每个帖子回复转换为Post对象.
>构建UserPost对象的集合,每个对象都有一个用户对象和用户发布的帖子列表.

public class UserPosts {

private final User user;
private final List

}

我目前实现如下:

package com.@R_301_5@;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.@R_301_5@;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.asynchttpclient.Response;

import com.http.HttpResponse;
import com.http.HttpUtil;
import com.model.Post;
import com.model.User;
import com.model.UserPosts;

/**
 * Created by vm on 8/20/18.
 */

class UserPostResponse {
    private final User user;
    private final Future301_5@ extends HttpResponse {
    private Function301_5@() {
        super(HttpUtil.getInstance());
    }

    public List301_5@301_5@
                    .supplyAsync(() -> super.getUsers())
                    .thenApply(userResponseToObject)
                    .thenApply((List

但是,我不确定我这样做的方式是否正确.更具体地说,在userResponseToObject和postResponseToObject函数中,我调用Future上的get()方法,它将被阻塞.

有没有更好的方法来实现这个?

最佳答案
如果您打算使用@R_301_5@,则应使用async-http-client库中的ListenableFuture. ListenableFuture可以转换为@R_301_5@.

使用@R_301_5@的优点是您可以编写处理Response对象的逻辑,而无需了解有关期货或线程的任何信息.假设您编写了以下4种方法. 2发出请求,2发表解析:

ListenableFuture

现在我们可以编写一个非阻塞方法来检索给定用户的帖子:

@R_301_5@301_5@()
        .thenApply(r -> parseUserPosts(r,u));
}

和阻止方法来读取所有用户的所有帖子:

List301_5@301_5@()
            .thenApply(userRequest -> parseUsers(userRequest)
                    .stream()
                    .map(this::userPosts)
                    .collect(toList())
            ).join();


    // collect the results
    return postFutures.stream()
            .map(@R_301_5@::join)
            .flatMap(List::stream)
            .collect(toList());
}
原文链接:https://www.f2er.com/java/437508.html

猜你在找的Java相关文章