[英]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.