探究WebClient的block和subscribe call有无return的服务的区别
Java代码
Server
Server1
@RequestMapping("/server1")
public void server1(){
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("server1 is executing");
}
log.info("server1 is done");
}
Server2
@RequestMapping("/server2")
public String server2(){
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("server2 is executing");
}
log.info("server2 is done");
return "server2's return";
}
Client
client1
@RequestMapping("/client1")
public void client1() {
log.info("block call 无return");
Void block = webClient.get().uri("/server1").retrieve().bodyToMono(Void.class).block();
log.info("client1 finished");
}
client2
@RequestMapping("/client2")
public void client2() {
log.info("block call 有return");
String block = webClient.get().uri("/server2").retrieve().bodyToMono(String.class).block();
log.info("client2 finished");
}
client3
@RequestMapping("/client3")
public void client3() {
log.info("subscribe call 无return");
Disposable subscribe = webClient.get().uri("/server1").retrieve().bodyToMono(Void.class).subscribe();
log.info("client3 finished");
}
client4
@RequestMapping("/client4")
public void client4() {
log.info("subscribe call 有return");
Disposable subscribe = webClient.get().uri("/server2").retrieve().bodyToMono(String.class).subscribe();
log.info("client4 finished");
}
控制台输出
Block call 无return
Block call 有return
Subscribe call 无return
Subscribe call 有return
结论
Block同步,subscribe异步。与call的服务有没有return无关