reactive-programming - Spring WebFlux如何合并Mono Objects的结果?
问题描述
请查看使用 RestTemplate 的控制器(添加评论)的以下代码:
@GetMapping("/{courseid}")
public Course getCourseDetails(@PathVariable Long courseid) {
// Get Course info (ID, Name, Description) from pre-populated Array List
CourseInfo courseInfo = getCourseInfo(courseid);
// Get Price info of a course from another microservice using RESTTemplate
Price price = restTemplate.getForObject("http://localhost:8002/price/"+courseid, Price.class);
// Get enrollment info of a course from another microservice using RESTTemplate
Enrollment enrollment = restTemplate.getForObject("http://localhost:8003/enrollment/"+courseid, Enrollment.class);
//Consolidate everything in to Course object and send it as response
return new Course(courseInfo.getCourseID(), courseInfo.getCourseName(), courseInfo.getCourseDesc(), price.getDiscountedPrice(),
enrollment.getEnrollmentOpen());
}
现在我正在尝试使用反应式编程来实现相同的目标。我现在使用来自 Web-Flux 的 WebClient 和 Mono。但是,我很困惑如何组合结果?看看下面的代码(只是使用 Mono Everywhere。其余代码保持不变)
@GetMapping("/{courseid}")
public Mono<Course> getCourseDetails(@PathVariable Long courseid) {
// Get Course info (ID, Name, Description) from pre-populated Array List
CourseInfo courseInfo = getCourseInfo(courseid);
// Get Price info of a course from another microservice using RESTTemplate
Mono<Price> price = webClient.get().uri("http://localhost:8002/price/{courseid}/",courseid).retrieve().bodyToMono(Price.class);
// Get enrollment info of a course from another microservice using RESTTemplate
Mono<Enrollment> inventory = webClient.get().uri("http://localhost:8003/enrollment/{courseid}/",courseid).retrieve().bodyToMono(Enrollment.class);
//Question : How do we Consolidate everything and form a Mono<Course> object and send it as response?
}
问题 1:我们如何合并所有内容并形成 Mono 对象并将其作为响应发送?
问题2:语句“CourseInfo courseInfo = getCourseInfo(courseid);”是否 导致阻塞操作?
谢谢!
解决方案
restTemplate.getForObject
返回简单对象 - 在您的情况下Price
或Enrollment
. 您可以简单地将它们转换为 MonoMono.just(object)
,但更好的解决方案是切换到Webclient,它是 Spring Reactive 的默认 HTTP 客户端getCourseInfo
这取决于这种方法背后的逻辑是什么。确定该方法后面是否存在 JDBC 连接,它是阻塞的。要与您做出最终回应,
Mono<Course>
您应该考虑zip 运算符,这将帮助您。
例如:
Mono<Course> courseMono = Mono.zip(price, enrollment)
.map(tuple -> new Course(courseInfo, tuple.getT1(), tuple.getT2()));
推荐阅读
- contentful - 如何使用 ruby on rails 仅使用 url insted 的 entry-id 获取内容条目?
- java - 令牌“{”上的语法错误,在此令牌切换 (char) 之后需要 SwitchLabels
- amazon-web-services - 如果运行的底层 Powershell 脚本失败,如何使 Ansible 任务失败?
- c# - 不正确的警告将 null 文字或可能的 null 值转换为不可为 null 的类型
- reactjs - 在 rooks 中使用 useDebounce 时如何设置加载为真?
- javascript - 为什么这个 getter 方法在 React 中被调用了多次?
- azure-service-fabric - Service Fabric 中的 Stateless Worker 服务在同一进程中重新启动
- c# - 如何在 C# 的套接字程序中通过网络发送/接收数据
- reactjs - 如何将组件从子组件注入根组件?
- python - 如何在python中检测部分字符串中的部分模式