普通的Controller
@GetMapping("/1")
public String fun1() {
log.info("get str in fun1 start");
String str = createStr();
log.info("get str in fun1 end");
return str;
}
后台log日志:
可以看出,请求fun1()这个controller用了单个线程去跑并且返回,任务耗时10秒,则方法调用开始到结束用时10秒
Mono
@GetMapping("/2")
public Mono<String> fun2() {
log.info("get str in fun2 start");
Mono<String> stringMono = Mono.fromSupplier(this::createStr);
log.info("get str in fun2 end");
return stringMono;
}
应为采用了异步FLUX编程模型,在这个方法内,主线程会为工作方法开一个线程去跑,而主线程立即返回,不发生阻塞,直到工作线程调用结束之后,将结果返回给前端
Flux
@GetMapping(value = "/3",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> fun3() throws InterruptedException {
log.info("get str in fun2 start");
Flux<String> result = Flux.fromStream(IntStream.range(1, 5).mapToObj(x -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return String.valueOf(x);
}));
log.info("get str in fun2 end");
return result;
}
执行结果: