我正在使用Spring WebFlux开发具有Reactive支持的Microservices应用程序 . 让我们看看,我有一个问题列表属于一个类别和每个问题的选项列表 . 我将问题和选项分离到具有Reactive支持的服务中,我希望使用另一个服务将它们组合在一起使用Spring WebFlux的WebClient . 当然,它也需要支持Reactive .
QuestionServiceImpl:
public Flux<Question> getQuestions(String categoryId) {
WebClient client = WebClient
.builder()
.baseUrl(getServiceUrl())
.build();
WebClient.ResponseSpec responseSpec = client
.get()
.uri("/questions/" + categoryId)
.retrieve();
return responseSpec.bodyToFlux(Question.class);
}
OptionServiceImpl:
public Flux<Option> getOptions(String questionId) {
WebClient client = WebClient
.builder()
.baseUrl(getServiceUrl())
.build();
WebClient.ResponseSpec responseSpec = client
.get()
.uri("/options/" + questionId)
.retrieve();
return responseSpec.bodyToFlux(Option.class);
}
但我不知道如何以反应方式将问题与其选项结合起来 . 有谁能提出一些想法?
更新的方案:
我添加了一个名为CompositeQuestion的新类
@Data
@AllArgsConstructor
public class CompositeQuestion {
private String id;
private String description;
private String categoryId;
private List<Option> options;
}
现在要获取问题的列表选项,我的代码如下:
Flux<CompositeQuestion> compositQuestion = questionsFromCoreQuestionService.flatMap(question ->
optionService.getOptions(question.getId())
.collectList()
.map(options -> new CompositeQuestion(question.getId(), question.getDescription(), question.getCategoryId(), options)))
.subscribeOn(Schedulers.elastic());
1 回答
我们假设你有一个类如下的类:
(@Value注释来自Lombok)
您可以使用以下选项检索问题:
请注意,如果类别的顺序可能与您请求的顺序不同 . 如果这对您来说是一个交易破坏者,您可以考虑使用concatMap()而不是flatMap(),尽管每个请求将按顺序运行 .