我试图理解Java 8中的CompletableFuture.作为其中的一部分,我正在尝试进行一些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.CompletableFuture;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
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 FutureCompletableFuture extends HttpResponse {
private FunctionetoObject = user -> {
try {
return super.convertResponsetoUser(Optional.of(user.get().getResponseBody())).get();
} catch (Exception e) {
e.printstacktrace();
return null;
}
};
private FunctionetoObject = post -> {
try {
return super.convertResponsetoPost(Optional.of(post.get().getResponseBody())).get();
} catch (Exception e) {
e.printstacktrace();
return null;
}
};
private FunctionetoObject.apply(userPostResponse.getPostResponse()));
} catch (Exception e) {
e.printstacktrace();
return null;
}
};
private FunctionCompletableFuture() {
super(HttpUtil.getInstance());
}
public ListCompletableFutureCompletableFuture
.supplyAsync(() -> super.getUsers())
.thenApply(userResponsetoObject)
.thenApply((Liststem.out.println(users);
return users;
} catch (Exception e) {
e.printstacktrace();
}
return null;
}
}
但是,我不确定我这样做的方式是否正确.更具体地说,在userResponsetoObject和postResponsetoObject函数中,我调用Future上的get()方法,它将被阻塞.
有没有更好的方法来实现这个?
使用CompletableFuture的优点是您可以编写处理Response对象的逻辑,而无需了解有关期货或线程的任何信息.假设您编写了以下4种方法. 2发出请求,2发表解析:
ListenableFuture
CompletableFutureCompletableFuture()
.thenApply(r -> parseUserPosts(r,u));
}
ListCompletableFutureCompletableFuture()
.thenApply(userRequest -> parseUsers(userRequest)
.stream()
.map(this::userPosts)
.collect(toList())
).join();
// collect the results
return postFutures.stream()
.map(CompletableFuture::join)
.flatMap(List::stream)
.collect(toList());
}
原文地址:https://www.jb51.cc/java/437508.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。