异步Java CompletableFuture获取其请求
我正在创建CompletableFuture
列表,用于创建一些异步请求。然而,当我得到它的回应时,我不知道我得到的是哪种回应。有没有办法知道通过^{
下面是CompletableFuture
列表的代码,该列表的结果需要与其请求进行映射
List<CompletableFuture<UserResponse>> userResponse = new ArrayList<>();
for (User user: users) {
UserRequest userRequest = UserRequest.builder()
.id(id)
.build();
CompletableFuture<UserResponse> userCompletableFuture = this.userClient
.checkUserRequest(
userRequest
);
userResponse.add(userCompletableFuture);
}
CompletableFuture.allOf(userCompletableFutures.toArray(new CompletableFuture[0]))
.exceptionally(ex -> null)
.join();
IntStream.range(0, userCompletableFutures.size())
.forEach(index -> {
try {
UserResponse userResponse = userCompletableFutures.get(index).get();
// Do something with the response and map it with the request.
} catch (Exception e) {
e.printStackTrace();
}
});
这里是UserClient
@Async
public CompletableFuture<UserResponse> checkUserRequest(UserRequest request) {
CheckUserUrl url = new CheckUserUrl(apiUrl);
return CompletableFuture.supplyAsync(() ->
this.sendHttpRequest(
HttpRequestDTO.builder()
.url(url)
.httpMethod(HttpMethod.POST)
.request(new HttpEntity<>(request))
.build(),
UserResponse.class
)
);
}
共 (0) 个答案