核心思想
WebFlux主要是异步
例子
参考一个源码:
https://blog.youkuaiyun.com/qq_43923045/article/details/106309432?spm=1001.2014.3001.5506
@GetMapping("/delay1")
public Mono<RestResult> delayResult() {
long l = System.currentTimeMillis();
Mono<RestResult> resultMono = Mono.fromSupplier(()->{
try {
Thread.sleep(5_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new RestResult().setMessage("hello world!!");
});
long r = System.currentTimeMillis();
log.info("执行时间 {} !!",(r-l));
return resultMono;
}
@GetMapping("/delay2")
public RestResult delayResult2() {
long l = System.currentTimeMillis();
Supplier<RestResult> result = () -> {
try {
Thread.sleep(5_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new RestResult<>().setMessage("ok");
};
RestResult restResult = result.get();
long r = System.currentTimeMillis();
log.info("执行时间 {} !!",(r-l));
return restResult;
}
如上面的代码例子,delay1接口会直接打印执行时间。delay2会等待一段时间才能打印执行时间。
扩展
思考:
对于delay1接口,什么时候才有返回结果呢?
答案:
返回需要加上MediaType.APPLICATION_STREAM_JSON_VALUE
@GetMapping(value = "/stream",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
参考资料https://blog.youkuaiyun.com/weixin_34364071/article/details/91664821?spm=1001.2014.3001.5506
遗留问题
1、那使用postman等工具测试例子的2个接口的时间到底是多少?
2、前端怎么去处理异步返回的结果?