gpt4 book ai didi

java - 从 CompletableFuture 获取响应

转载 作者:行者123 更新时间:2023-12-04 07:27:20 25 4
gpt4 key购买 nike

我正在尝试添加 Async到我从 db 的 fetch 操作。但是,我一直在尝试从 CompletableFuture.allOf() 获得响应。 .加入返回一个'void。相反,我怎样才能返回 List<QuestionResponseData>如代码中所述。下面是我的代码

@RequestMapping(method = RequestMethod.POST, path = "/questionsByAssessmentIdAndQuestionNumber")
public List<QuestionResponseData> getQuestionsByIdAndLimit(@RequestBody QuestionOptionRequest questionOptionRequest) {
String assessmentId = questionOptionRequest.getAssessmentId();
QuestionOptionRequest request = QuestionOptionRequest.builder().assessmentId(questionOptionRequest.getAssessmentId()).startingQuestion(1).build();
CompletableFuture<List<QuestionResponseData>> questions = questionService.getQuestions(request);
QuestionOptionRequest request1 = QuestionOptionRequest.builder().assessmentId(assessmentId).startingQuestion(26).build();
CompletableFuture<List<QuestionResponseData>> questions1 = questionService.getQuestions(request1);
QuestionOptionRequest request2 = QuestionOptionRequest.builder().assessmentId(assessmentId).startingQuestion(51).build();
CompletableFuture<List<QuestionResponseData>> questions2 = questionService.getQuestions(request2);
QuestionOptionRequest request3 = QuestionOptionRequest.builder().assessmentId(assessmentId).startingQuestion(76).build();
CompletableFuture<List<QuestionResponseData>> questions3 = questionService.getQuestions(request3);

CompletableFuture.allOf(questions, questions1, questions2, questions3).join();

//return questionService.getQuestions(questionOptionRequest);
}

最佳答案

 CompletableFuture<List<QuestionResponseData>> futures = new CompletableFuture[]{request, request1, request2, request3};

List<QuestionResponseData> result =
CompletableFuture.allOf(futures)
.thenApply(_void -> Arrays.stream(futures).map(CompletableFuture::join).flatMap(List::stream).collect(Collectors.toList()))
.join();
请注意,调用 CompletableFuture::join实际上并没有阻塞,阻塞已经发生在 CompletableFuture::allOf

关于java - 从 CompletableFuture 获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68141771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com