【发布时间】:2020-08-24 21:05:55
【问题描述】:
我们正在尝试将 MVC、resttemplate、blocking、应用程序转换为 WebFlux 应用程序。
在“阻塞世界”中非常简单,在请求负载中获取一个列表,遍历它并将 N 个 http 请求发送到第三方 rest API。
很重要的是第三方rest API,根本无法控制,也不能要求他们实现一个取列表的版本,必须一个一个。
resttemplate 很简单,请问 WebFlux 的等价物是什么? 这有点挑战性,因为它需要一个 Mono 并返回一个 Mono。 一个小的 sn-p 会很棒。
谢谢
@SpringBootApplication
@RestController
public class QuestionApplication {
public static void main(String[] args) {
SpringApplication.run(QuestionApplication.class, args);
}
@PostMapping("question")
MyResponse question(@RequestBody MyRequest myRequest) {
List<String> myStrings = myRequest.getListOfString();
List<Integer> myIds = iterateAndSendRequestOneByOneGetIdFromString(myStrings);
return new MyResponse(myIds);
}
private List<Integer> iterateAndSendRequestOneByOneGetIdFromString(List<String> myStrings) {
List<Integer> ids = new ArrayList<>();
for (String string : myStrings) {
Integer id = new RestTemplate().postForObject("http://external-service:8080/getOneIdFromOneString", string, Integer.class);
ids.add(id);
}
return ids;
}
// @PostMapping("how-to-do-the-same-with-WebFlux-WebClient-please?")
// Mono<MyResponse> question(@RequestBody Mono<MyRequest> myRequestMono) {
// return null;
// }
}
class MyResponse {
private List<Integer> myIds;
}
class MyRequest {
private List<String> strings;
}
【问题讨论】:
-
你试过什么?
标签: java spring spring-webflux spring-webclient