[英]Reactive Spring WebClient calls
我正在尝试了解 WebFlux,但在 Webclient 调用方面遇到了一些麻烦。 我没有看到这一行 System.out.println("customerId = " + customerId); 执行它似乎没有调用端点。 但是如果我用 .subscribe(customer -> {}); 订阅 webclient; 然后我可以看到这一行 System.out.println("customerId = " + customerId); 在端点端工作。 我不明白为什么我必须订阅 Mono 调用,还是必须订阅? 谢谢
@GetMapping("/customer/{customerId}")
@ResponseStatus(HttpStatus.ACCEPTED)
public Mono<Void> getCustomer(@PathVariable("customerId") int customerId) {
WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
webClient.get()
.uri("/client/customer/{customerId}",customerId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Customer.class);//here do I have to subscribe to actually activate to call?
return null;
}
@GET
@Path("/customer/{customerId}")
@Produces(MediaType.APPLICATION_JSON)
public Customer getCustomer(@PathParam("customerId") int customerId) throws InterruptedException {
System.out.println("customerId = " + customerId); // I do not see the call comes thru if I dont subscribe to flux call.
return new Customer(customerId,"custName");
}
如果要从WebClient
返回反应类型,则必须从控制器方法返回它,例如:
@GetMapping("/customer/{customerId}")
@ResponseStatus(HttpStatus.ACCEPTED)
public Mono<Customer> getCustomer(@PathVariable("customerId") int customerId) {
WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
return webClient.get()
.uri("/client/customer/{customerId}",customerId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Customer.class);
}
您还可以从您的端点返回一个Customer
并阻止并等待您的WebClient
的结果并离开响应式生态系统,例如:
@GetMapping("/customer/{customerId}")
@ResponseStatus(HttpStatus.ACCEPTED)
public Customer getCustomer(@PathVariable("customerId") int customerId) {
WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
return webClient.get()
.uri("/client/customer/{customerId}",customerId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Customer.class)
.block()
}
如果您正在查看 Spring 的WebClient
的一般介绍,请查看本教程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.